본문으로 바로가기

[ 문제 ]

<그림 1>과 같이 정사각형 모양의 지도가 있다.

1은 집이 있는 곳을, 0은 집이 없는 곳을 나타낸다.

 

철수는 이 지도를 가지고 연결된 집의 모임인 단지를 정의하고, 단지에 번호를 붙이려 한다.

여기서 연결되었다는 것은 어떤 집이 좌우, 혹은 아래위로 다른 집이 있는 경우를 말한다.

대각선상에 집이 있는 경우는 연결된 것이 아니다.

<그림 2>는 <그림 1>을 단지별로 번호를 붙인 것이다.

 

지도를 입력하여 단지수를 출력하고, 각 단지에 속하는 집의 수를 오름차순으로 정렬하여 출력하는 프로그램을 작성하시오.

 

[ 입력 ]

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

 

[ 출력 ]

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

 

[ 예제 입력 ]

7

0110100

0110101

1110101

0000111

0100000

0111110

0111000

 

[ 예제 출력 ]

3

7

8

9

 


import java.util.*;
import java.io.*;

public class Main_BJ_2667_단지번호붙이기 {
	
	static class House {
		int row, column;
		House(int row, int column){
			this.row = row;
			this.column = column;
		}
	}
	
	static int N;
	static char[][] map;
	static boolean[][] visited;
	
	static int[] dr = {-1, 1, 0, 0};
	static int[] dc = {0, 0, -1, 1};
	
	static ArrayList<Integer> count;
	
	public static void bfs (int row, int column) {
		House current = new House(row, column);
		Queue<House> queue = new LinkedList<>();
		queue.offer(current);
		int cnt = 1;
		
		while (!queue.isEmpty()) {
			current = queue.poll();
			
			for (int d = 0; d < 4; d++) {
				if (current.row+dr[d] >= 0 && current.row+dr[d] < N && current.column+dc[d] >= 0 && current.column+dc[d] < N
						&& !visited[current.row+dr[d]][current.column+dc[d]] && map[current.row+dr[d]][current.column+dc[d]] == '1') {
					visited[current.row+dr[d]][current.column+dc[d]] = true;
					queue.offer(new House(current.row+dr[d], current.column+dc[d]));
					cnt++;
				}
			}
		}
		count.add(cnt);
	}


	public static void main(String[] args) throws Exception {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		N = Integer.parseInt(br.readLine()); // 지도의 크기
		
		map = new char[N][N];
		for (int i = 0; i < N; i++) map[i] = br.readLine().toCharArray();
		
		visited = new boolean[N][N];
		count = new ArrayList<>();
		int cnt = 0; // 단지 수
		
		for (int i = 0; i < N; i++) {
			for (int j = 0; j < N; j++) {
				if (!visited[i][j] && map[i][j]=='1') {
					visited[i][j] = true;
					cnt++;
					bfs(i, j);
				}
			}
		}
		
		Object[] c = count.toArray();
		Arrays.sort(c);
		
		System.out.println(cnt);
		for (Object i: c) System.out.println(i);
	}
}