출처

2667번: 단지번호붙이기

문제

<그림 1>과 같이 정사각형 모양의 지도가 있다. 1은 집이 있는 곳을, 0은 집이 없는 곳을 나타낸다. 철수는 이 지도를 가지고 연결된 집의 모임인 단지를 정의하고, 단지에 번호를 붙이려 한다. 여기서 연결되었다는 것은 어떤 집이 좌우, 혹은 아래위로 다른 집이 있는 경우를 말한다. 대각선상에 집이 있는 경우는 연결된 것이 아니다. <그림 2>는 <그림 1>을 단지별로 번호를 붙인 것이다. 지도를 입력하여 단지수를 출력하고, 각 단지에 속하는 집의 수를 오름차순으로 정렬하여 출력하는 프로그램을 작성하시오.

https://www.acmicpc.net/upload/images/ITVH9w1Gf6eCRdThfkegBUSOKd.png

입력

첫 번째 줄에는 지도의 크기 N(정사각형이므로 가로와 세로의 크기는 같으며 5≤N≤25)이 입력되고, 그 다음 N줄에는 각각 N개의 자료(0혹은 1)가 입력된다.

출력

첫 번째 줄에는 총 단지수를 출력하시오. 그리고 각 단지내 집의 수를 오름차순으로 정렬하여 한 줄에 하나씩 출력하시오.

예제 입력 1

7
0110100
0110101
1110101
0000111
0100000
0111110
0111000

예제 출력 1

3
7
8
9

문제접근

DFS로 접근하되, 1을 만날때마다 값을 갱신해주어야 하므로 중복되지 않기 위해, 2부터 네이밍을 해주었습니다.

코드

package main.java;
import java.util.*;
public class NumberingTown {
    static int number;
    static int[][] graph;
    static boolean[][] visited;
    static int count=2; //1과 중복되지 않기위해 2로 초기화
    static int[] di={-1,1,0,0};
    static int[] dj={0,0,-1,1};
    static HashMap<Integer,Integer>result = new HashMap<>();
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        number=in.nextInt();
        String item;
        graph= new int[number][number];
        visited = new boolean[number][number];
        char[] chars;
        for(int i = 0; i<number;i++){
            item=in.next();
            chars=item.toCharArray();
            for(int j = 0; j<chars.length;j++){
                graph[i][j]=Character.getNumericValue(chars[j]);
            }
        }
				// graph 입력
        for(int i = 0; i<number;i++){
            for(int j = 0; j<number;j++){
                if(graph[i][j]==1){
                    DFS(i,j,count); // 상하좌우 연결된 마을을 count로 치환
                    count++;
                }
            }
        }
        for(int i = 0; i<number;i++){
            for(int j = 0; j<number;j++){
                if(graph[i][j]!=0){
										//HashMap을 통해 출력형식을 맞춥니다.
                    result.put(graph[i][j],result.getOrDefault(graph[i][j],0)+1);
                }
            }
        }
        System.out.println(result.size());
        ArrayList<Integer>values= new ArrayList<>();
        for(int x : result.keySet()){
            values.add(result.get(x));
        }
        Collections.sort(values);
        for(int x : values){
            System.out.println(x);
        }
    }
    public static void DFS(int startI,int startJ,int count){
        if(graph[startI][startJ]==0){
						//집이 아닌 경우 종료
            return;
        }else{
						//단지번호 붙이기 && 방문처리
            graph[startI][startJ]=count;
            visited[startI][startJ]=true;
            for(int i = 0; i<di.length;i++){
								//상하좌우 탐색
                int nextI=startI+di[i];
                int nextJ=startJ+dj[i];
                if(nextI>=0&&nextI<number&&nextJ>=0&&nextJ<number&&!visited[nextI][nextJ]){
                    DFS(nextI,nextJ,count);
                }
            }
        }
    }
}