문제
입력 및 출력
풀이
import java.io.*;
import java.util.*;
class Main {
public static int N;
public static int[][] map;
public static boolean[][] visited;
public static int count;
public static int[] dx = {0, 1, 0 ,-1};
public static int[] dy = {1, 0, -1, 0};
public static void main(String args[]) throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
ArrayList<Integer> list = new ArrayList<>();
N = Integer.parseInt(br.readLine());
visited = new boolean[N][N];
map = new int[N][N];
for(int i = 0; i < N; i++) {
String[] temp = br.readLine().split("");
for(int j = 0; j < temp.length; j++) {
map[i][j] = Integer.parseInt(temp[j]);
}
}
for(int i = 0; i < N; i++) {
for(int j = 0; j < N; j++) {
if(!visited[i][j] && map[i][j] == 1) {
count = 0;
DFS(i, j);
list.add(count);
}
}
}
Collections.sort(list);
System.out.println(list.size());
for(int i : list) {
System.out.println(i);
}
}
public static void DFS(int x, int y) {
visited[x][y] = true;
count++;
for(int i = 0; i < 4; i++) {
int nx = x + dx[i];
int ny = y + dy[i];
if(nx < 0 || ny < 0 || nx >= N || ny >= N) {
continue;
}
if(!visited[nx][ny] && map[nx][ny] == 1) {
visited[nx][ny] = true;
DFS(nx, ny);
}
}
}
}
결과 및 해결방법
[결과]