๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
์•Œ๊ณ ๋ฆฌ์ฆ˜/๋ฌธ์ œ

[์ž๋ฐ”] ๋ฐฑ์ค€ 2667 - ๋‹จ์ง€๋ฒˆํ˜ธ๋ถ™์ด๊ธฐ

by applemango2021 2020. 12. 6.

ํ’€๋•Œ๋งˆ๋‹ค ์ƒˆ๋กญ๋‹ค. ์‹ ๊ธฐํ•˜๋‹ค.

๋„ค ๋ฐฉํ–ฅ์„ ์™”๋‹ค ๊ฐ”๋‹ค ํ•  ์ˆ˜ ์žˆ๋„๋ก 2์ฐจ์› int๋ฐฐ์—ด์„ ๋งŒ๋“ค์–ด์„œ for๋ฌธ์œผ๋กœ ํ•˜๋‚˜์”ฉ que์— ๋‹ด์•„์ฃผ๋Š” ๋ถ€๋ถ„์ด ํ•ญ์ƒ ํ—ท๊ฐˆ๋ฆฐ๋‹ค.

 int[][] dir = { {0,1}, {0,-1}, {1,0}, {-1,0} }; 

BFS์—์„œ๋Š” que ์•ˆ์—์„œ if๋ฌธ์˜ ์กฐ๊ฑด์„ ์ œ๋Œ€๋กœ ์„ธ์šฐ๋Š” ๋‹จ๊ณ„๊ฐ€ ์ œ์ผ ๊นŒ๋‹ค๋กญ๊ฒŒ ๋Š๊ปด์ง„๋‹ค.

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.Queue;

public class Main2667_๋‹จ์ง€๋ฒˆํ˜ธ๋ถ™์ด๊ธฐ {
	
	static int N;
	static int[][] map;
	static boolean[][] visited;
	public static void main(String[] args) throws Exception {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		StringBuilder sb = new StringBuilder();
		N = Integer.parseInt(br.readLine().trim());
		map = new int[N][N];
		visited = new boolean[N][N];
		
		String[] str;
		
		for(int n=0;n<N;n++) {
			str = br.readLine().trim().split("");
			for(int m=0;m<N;m++) {
				map[n][m] = Integer.parseInt(str[m]);
			}
		}
		
		//bfs ๋ฉ”์†Œ๋“œ๋ฅผ ํ†ตํ•ด์„œ map[][]์— ๋‹จ์ง€๋ฒˆํ˜ธ๋ฅผ ๋ถ™์ธ๋‹ค 
		//danjiNum = 1์„ ํ•œ ๋‹ค์Œ์—, ์‹ค์ œ๋กœ๋Š” 2๋ถ€ํ„ฐ ์‹œ์ž‘ํ•˜๋„๋ก ํ•œ๋‹ค
		//๋‹จ์ง€๊ฐ€ ์žˆ๊ณ  ์—†๊ณ ์˜ ์—ฌ๋ถ€๋ฅผ ์ฒดํฌํ•˜๋Š” 1์ด๋ž‘ ๊ฒน์น˜๋ฉด ์•ˆ๋˜๋‹ˆ๊นŒ! 
		int danjiNum = 1;
		for(int x=0;x<N;x++) {
			for(int y=0;y<N;y++) {
				if(map[x][y]==1 && !visited[x][y]) {
					danjiNum ++;
					bfs(x,y,danjiNum);
				}
			}
		}
		
		//map[]์„ ๋‹ค์‹œ ๋Œ๋ฉด์„œ ๊ฐ danjiNum๋งˆ๋‹ค ๋ช‡ ๊ฐœ์˜ ๋‹จ์ง€๊ฐ€ ํฌํ•จ๋˜์–ด ์žˆ๋Š”์ง€ ์นด์šดํŠธํ•œ๋‹ค
		//์ด๋•Œ ๋‹จ์ง€๋ฒˆํ˜ธ๋Š” 2๋ฒˆ๋ถ€ํ„ฐ ์‹œ์ž‘ํ•˜๋ฏ€๋กœ 
		int[] cntDanji = new int[danjiNum+2];
		for(int n=0;n<N;n++) {
			for(int m=0;m<N;m++) {
				if(map[n][m]>1) cntDanji[map[n][m]]++;
			}
		}
		
		ArrayList<Integer> list = new ArrayList<Integer>();
		for(int i=2;i<=danjiNum;i++) {
			list.add(cntDanji[i]);
		}
		
		Collections.sort(list);
		sb.append(danjiNum-1+"\n");
		for (Integer i : list) {
			sb.append(i+"\n");
		}
		
		System.out.println(sb.toString().trim());
		
	}

	private static void bfs(int x, int y, int danjiNum) {
		visited[x][y] =  true;
		map[x][y] = danjiNum;
		
		Queue<int[]> que = new LinkedList<int[]>();
		que.add(new int[] {x,y});
		
		int[] tmp;
		int tmpX, tmpY;
		int newX, newY;
		while(!que.isEmpty()) {
			tmp = que.poll();
			tmpX = tmp[0];
			tmpY = tmp[1];
			
			int[][] dir = { {0,1}, {0,-1}, {1,0}, {-1,0} };
			for(int d=0;d<4;d++) {
				newX = tmpX + dir[d][0];
				newY = tmpY + dir[d][1];
				
				if(newX>=0 && newX<N && newY>=0 && newY<N 
						&& !visited[newX][newY] && map[newX][newY]==1) {
					visited[newX][newY] = true;
					map[newX][newY] = danjiNum;
					que.offer(new int[] {newX, newY});
				}
			}
		}
	}
}