본문 바로가기
알고리즘/코딩 - 백준

[Java][자바][백준][2667번] 단지 번호 붙이기

by 주남2 2019. 8. 22.
반응형

문제 설명

<그림 1>과 같이 정사각형 모양의 지도가 있다. 1은 집이 있는 곳을, 0은 집이 없는 곳을 나타낸다. 철수는 이 지도를 가지고 연결된 집들의 모임인 단지를 정의하고, 단지에 번호를 붙이려 한다. 여기서 연결되었다는 것은 어떤 집이 좌우, 혹은 아래위로 다른 집이 있는 경우를 말한다. 대각선상에 집이 있는 경우는 연결된 것이 아니다. <그림 2>는 <그림 1>을 단지별로 번호를 붙인 것이다. 지도를 입력하여 단지수를 출력하고, 각 단지에 속하는 집의 수를 오름차순으로 정렬하여 출력하는 프로그램을 작성하시오.

입력

첫 번째 줄에는 지도의 크기 N(정사각형이므로 가로와 세로의 크기는 같으며 5≤N≤25)이 입력되고, 그 다음 N줄에는 각각 N개의 자료(0혹은 1)가 입력된다.

출력

첫 번째 줄에는 총 단지수를 출력하시오. 그리고 각 단지내 집의 수를 오름차순으로 정렬하여 한 줄에 하나씩 출력하시오.

 

생각

연결성분을 확인해서 번호를 붙여주면 되고, bfs를 이용해 큐에 들어가는 단지의 수를 각각 구해주면 된다! 자세한 설명은 주석으로 적겠다.

 

코드

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.*;
 
public class Main {
    //static 변수를 설정한다. 각 단지의 넓이를 담을 ArrayList를 만든다.
    //count_danzi : 마을 번호를 식별해줄 변수이다.
    static int n;
    static int[][] map;
    static boolean[][] visited;
    static int[] dx = {-1,1,0,0};
    static int[] dy = {0,0,-1,1};
    static int count_danzi = 0;
    static Queue<dot> q = new LinkedList<dot>();
    static ArrayList<Integer> arr = new ArrayList<Integer>();
    
    public static void main(String[] args) throws Exception{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    
        n = Integer.parseInt(br.readLine());
        
        map = new int[n][n];
        visited = new boolean[n][n];
        
        for(int i=0; i<n; i++) {
            String[] str = br.readLine().split("");
            for(int j=0; j<n; j++) {
                map[i][j] = Integer.parseInt(str[j]);
            }
        }
        
        for(int i=0; i<n; i++) {
            for(int j=0; j<n; j++) {
                if(!visited[i][j] && map[i][j] == 1) {
                    //방문하지 않아서 실행되는 경우 count_danzi를 증가시켜
                    //새로운 마을을 구분시켜준다.
                    bfs(new dot(i,j));
                    count_danzi++;
                }
            }
        }
        Collections.sort(arr);
        System.out.println(count_danzi);
        for(int i=0; i<arr.size(); i++) {
            System.out.println(arr.get(i));
        }
    }
    
    static void bfs(dot d) {
        //villege_count: while문을 돌면서 증가시키며 한 마을에서의 집의 수를 구한다.
        int villege_count = 0;
        visited[d.x][d.y] = true;
        q.add(d);
        
        while(!q.isEmpty()) {
            villege_count++;
            dot t = q.remove();
            int x1 = t.x;
            int y1 = t.y;
            
            for(int i=0; i<4; i++) {
                int x2 = x1 + dx[i];
                int y2 = y1 + dy[i];
                
                if(x2>=0 && x2<&& y2>=0 && y2<&& 
                        map[x2][y2] == 1 && !visited[x2][y2]) {
                    visited[x2][y2] = true;
                    q.add(new dot(x2,y2));
                }
            }
        }
        //while문을 나와 갯수가 구해지면 ArrayList에 넣어준다.
        arr.add(villege_count);
    }
}
 
class dot {
    int x;
    int y;
    
    public dot(int x,int y) {
        this.x = x;
        this.y = y;
    }
}
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
 
반응형