본문으로 바로가기

[BaekJoon] 백준 - 단지번호붙이기

category 알고리즘/백준 2022. 6. 16. 17:13

문제

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

입력

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

 

 

출력

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

 

 

 

2차원 배열을 순회하면서 1이 나오면 해당 집을 기준으로 단지를 BFS로 탐색한다.

BFS가 끝나면 다음 집을 찾아 새로운 단지를 탐색.

 

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
import java.util.stream.Collectors;

public class Main {
    static int N;
    static int M;
    static int[][] MAP;
    static boolean[][] visited;
    
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        
        String tmp = br.readLine();
       
        N = Integer.parseInt(tmp);
        
        MAP = new int[N][N];
        visited = new boolean[N][N];
        
        for(int i = 0; i<N; i++) {
            String[] input = br.readLine().split("");
            for(int j = 0; j<N; j++) {
                MAP[i][j] = Integer.parseInt(input[j]);
                visited[i][j] = false;
            }
        }
    
        List<Integer> list = new ArrayList<>();
        int[] x = {1, -1, 0, 0};
        int[] y = {0, 0, 1, -1};
        
        for(int i = 0; i<N; i++) {
            for(int j = 0; j<N; j++) {
                if (MAP[i][j] == 1 && !visited[i][j]) {
                    Queue<int[]> queue = new LinkedList<>();
                    queue.add(new int[]{i, j});
                    int count = 0;
                    
                    while(!queue.isEmpty()) {
                        int[] q = queue.poll();
                        visited[q[0]][q[1]] = true;
                        count++;
                        
                        for(int k = 0; k<4; k++) {
                            int ny = q[0] + y[k];
                            int nx = q[1] + x[k];
                            
                            if (ny >= 0 && ny < N && nx >= 0 && nx < N) {
                                if (MAP[ny][nx] == 1 && !visited[ny][nx]) {
                                    visited[ny][nx] = true;
                                    queue.add(new int[]{ny, nx});
                                }
                            }
                        }
                    }
                    
                    list.add(count);
                }
            }
        }
        
        list = list.stream().sorted(Comparator.comparing(Integer::intValue)).collect(Collectors.toList());
        
        System.out.println(list.size());
        
        for(int i = 0; i<list.size(); i++) {
            System.out.println(list.get(i));
        }
        
        
        
    }
    
}

 

'알고리즘 > 백준' 카테고리의 다른 글

[BaekJoon] 백준 - 게리맨더링 2  (0) 2022.06.23
[BaekJoon] 백준- 고층 건물 (Java)  (0) 2022.06.21
[BaekJoon] 백준 - 미로 탐색  (0) 2022.06.16
[BaekJoon] 백준 - 빙산  (0) 2022.06.15
[BaekJoon] 백준 - 스타트링크  (0) 2022.06.15