문제
<그림 1>과 같이 정사각형 모양의 지도가 있다. 1은 집이 있는 곳을, 0은 집이 없는곳을 나타낸다.
철수는 이 지도를 가지고 연결된 집의 모임인 단지를 정의하고, 단지에 번호를 붙이려 한다.
여기서 연결되었다는 것은 어떤 집이 좌우, 혹은 아래위로 다른 집이 있는 경우를 말한다.
대각선상에 집이 있는 경우는 연결된 것이 아니다. <그림 2>는 <그림 1>을 단지별로 번호를 붙인것이다.
지도를 입력하여 단지수를 출력하고, 각 단지에 속하는 집의 수를 오름차순으로 정렬하여 출력하는
프로그램을 작성하시오.
입력
7
0110100
0110101
1110101
0000111
0100000
0111110
0111000
출력
3
7
8
9
package Baekjoon;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
//백준 2583 - 단지 번호 붙이기 S1
public class ex6 {
static int n,cnt=1;
static ArrayList<Integer> arr = new ArrayList<>();
static int[][] board;
static int[][] ch;
static int[] dx={0,1,0,-1};
static int[] dy={-1,0,1,0};
public static void DFS(int x,int y,int[][] board){
ch[x][y]=1;
for(int i=0; i<4; i++){
int nx = x + dx[i];
int ny = y + dy[i];
if(nx>=0 && nx<n && ny>=0 && ny<n && board[nx][ny]==1 && ch[nx][ny]!=1){
cnt++;
DFS(nx,ny,board);
}
}
}
public static void solution(int[][] board){
for(int i=0; i<n; i++){
for(int j=0; j<n; j++){
if(board[i][j]==1 && ch[i][j]==0){
DFS(i,j,board);
arr.add(cnt);
cnt=1;
}
}
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
n=sc.nextInt();
board = new int[n][n];
ch = new int[n][n];
for(int i=0; i<n; i++){
String input = sc.next();
for(int j=0; j<n; j++){
board[i][j]=input.charAt(j)-'0';
//board[i][j]=Character.getNumericValue(input.charAt(j));
}
}
solution(board);
DFS(0,0,board);
Collections.sort(arr);
System.out.println(arr.size());
for(int x : arr){
System.out.println(x);
}
}
}
DFS 기본원리에 집중한 문제.