📍 문제 설명
💡 접근
전형적인 BFS 문제
👩💻 코드
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.*;
public class Main {
static int n, m, v, e, k, answer, cnt;
static int[][] board;
static int[] arr;
static long[] dp;
static boolean[][] visited;
static int[] dx = {-1,1,0,0};
static int[] dy = {0,0,-1,1};
static ArrayList<Integer> list = new ArrayList<>();
static StringBuilder sb = new StringBuilder();
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
Main T = new Main();
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
n = kb.nextInt();
kb.nextLine();
board = new int[n][n];
for(int i = 0; i < n; i++) {
String[] s = kb.nextLine().split("");
for(int j = 0; j < s.length; j++) {
board[i][j] = Integer.parseInt(s[j]);
}
}
visited = new boolean[n][n];
//모든 정점에 대해서 확인
for(int i = 0; i < n; i++) {
for(int j = 0; j < n; j++) {
cnt = 0;
if(board[i][j] == 1 && !visited[i][j]) {
answer++;
T.solution(i, j);
list.add(cnt);
}
}
}
System.out.println(answer);
Collections.sort(list);
for(int x : list) System.out.println(x);
}
private void solution(int x, int y) {
Queue<Point> q = new LinkedList<>();
q.offer(new Point(x, y));
visited[x][y] = true;
while(!q.isEmpty()) {
Point cp = q.poll();
for(int i = 0; i < 4; i++) {
int nx = cp.x + dx[i];
int ny = cp.y + dy[i];
if(nx<0 || ny<0 || nx>=n || ny>=n) continue;
if(board[nx][ny] == 1 && !visited[nx][ny]) {
board[nx][ny] = answer;
visited[nx][ny] = true;
q.offer(new Point(nx, ny));
}
}
cnt++;
}
}
private class Point {
private int x;
private int y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
}
}