2021년 10월 16일 토요일 12시
[DFSBFS] 백준_2667_단지번호붙이기_DFSBFS_실버1
https://www.acmicpc.net/problem/2667
import java.util.Arrays;
import java.util.Scanner;
public class Main{
private static int dx[] = {0,0,1,-1};
private static int dy[] = {1,-1,0,0};
private static int[] aparts = new int[25*25];
private static int n;
private static int apartNum = 0; //아파트 단지 번호의 수
private static boolean[][] visited = new boolean[25][25]; //방문여부
private static int[][] map = new int[25][25]; //지도
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
map = new int[n][n];
visited = new boolean[n][n];
//전체 사각형 입력 받기
for(int i=0; i<n; i++){
String input = sc.next();
for(int j=0; j<n; j++){
map[i][j] = input.charAt(j)-'0';
}
}
for(int i=0; i<n; i++){
for(int j=0; j<n; j++){
if(map[i][j] == 1 && !visited[i][j]){
apartNum++;
dfs(i,j);
}
}
}
Arrays.sort(aparts);
System.out.println(apartNum);
for(int i=0; i<aparts.length; i++){
if(aparts[i] == 0){
}else{
System.out.println(aparts[i]);
}
}
}
private static void dfs(int x, int y) {
visited[x][y] = true;
aparts[apartNum]++;
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){
if(map[nx][ny] == 1 && !visited[nx][ny]){
dfs(nx,ny);
}
}
}
}
}
/*
7
0110100
0110101
1110101
0000111
0100000
0111110
0111000
*/
<참고>
https://n1tjrgns.tistory.com/245
'알고리즘 > 백준' 카테고리의 다른 글
[DFSBFS] 백준_2178_미로탐색_DFSBFS_실버1 (0) | 2021.10.19 |
---|---|
[DFSBFS] 백준_1012_유기농배추_DFSBFS_실버2 (0) | 2021.10.19 |
[DFSBFS] 백준_2606_바이러스_DFSBFS_실버4 (0) | 2021.10.16 |
[DFSBFS] 백준_2606_바이러스_DFSBFS_실버4 (0) | 2021.10.14 |
[DFSBFS] 백준_1260_DFSBFS_DFSBFS_실버2 (0) | 2021.10.14 |