Lined Notebook

[Silver 1] [Java] 단지번호붙이기 (2667번)

by HeshAlgo

<단지번호붙이기>

문제 설명

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

제한 사항

입력

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

출력

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

내 생각

프로그래머스 문제 중 '카카오프렌즈 컬러링북(Level2)'처럼 구현하는 과정이 똑같은 문제라고 생각합니다.

BFS를 통해 문제를 해결 했고 인접한 단지를 방문할 때마다 카운트 값을 증가시켰고 인접한 단지를 모두 방문했을 경우 초기화 시켜 새로운 단지 수를 카운트 했습니다.

 

푼 시간

16분 49초

 

작성 코드

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
import java.util.*;
 
class Pair {
    int x;
    int y;
    Pair(int x, int y) {
        this.x = x;
        this.y = y;
    }
}
 
public class Main {
    
    public static final int[] dx = {001-1};
    public static final int[] dy = {1-100};
    
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        int n = scan.nextInt();
        int[][] map = new int[n][n];
        boolean[][] visited = new boolean[n][n]; 
         scan.nextLine();
         
        for (int i = 0; i < n; i++) {
            String str = scan.next();
            for (int j = 0; j < n; j++) {
                map[i][j] = str.charAt(j) - '0';
            }
        }
        List<Integer> answer = new ArrayList<Integer>();
        Queue<Pair> q = new LinkedList<Pair>();
        
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                if (!visited[i][j] && map[i][j] != 0) {
                    q.offer(new Pair(i, j));
                    visited[i][j] = true;
                    int danjiCount = 1;
                    
                    while (!q.isEmpty()) {
                        Pair pair = q.poll();
                        int x = pair.x;
                        int y = pair.y;
                        
                        for (int k = 0; k < 4; k++) {
                            int nx = x + dx[k];
                            int ny = y + dy[k];
                            
                            if (0 <= nx && nx < n && 0 <= ny && ny < n) {
                                if (!visited[nx][ny] && map[nx][ny] == 1) {
                                    danjiCount++;
                                    q.offer(new Pair(nx, ny));
                                    visited[nx][ny] = true;
                                    
                                }
                            }
                            
                        }
                        
                    }    // End of while
                    answer.add(danjiCount);
                }
            }
        }
        Collections.sort(answer);
        
        System.out.println(answer.size());
        for (int i = 0; i < answer.size(); i++) {
            System.out.println(answer.get(i));
        }
        
    }
 
}
 
 
 

 

실행 결과

블로그의 정보

꾸준히 공부하는 개발 노트

HeshAlgo

활동하기