[백준][2667번: 단지번호붙이기]

호준·2022년 2월 14일
0

Algorithm

목록 보기
26/111
post-thumbnail

문제

문제링크

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

입력

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

출력

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

코드

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.Queue;

public class Main {
    static int N;
    static int[] mx = {-1,1,0,0};
    static int[] my = {0,0,-1,1};
    static boolean[][] visited;
    static int[][] maps;
    static class Node{
        int x;
        int y;
        public Node(int x, int y) {
            this.x = x;
            this.y = y;
        }
    }
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        N = Integer.parseInt(br.readLine());
        maps = new int[N+1][N+1];
        visited = new boolean[N+1][N+1];
        // map 초기화
        for(int i=1; i<=N; i++){
            String[] str = br.readLine().split("");
            for(int j=1; j<=N; j++) {
                maps[i][j] = Integer.parseInt(str[j-1]);
            }
        }
        ArrayList<Integer> answer = new ArrayList<>();
        for(int i=1; i<=N; i++){
            for(int j=1; j<=N; j++){
                if(!visited[i][j] && maps[i][j]==1){
                    answer.add(BFS(i,j));
                }
            }
        }
        Collections.sort(answer); // 오름차순 정렬
        System.out.println(answer.size()); // answer의 크기 = 단지의 수
        for (int i = 0; i <answer.size() ; i++) {
            System.out.println(answer.get(i));
        }
    }
    static int BFS(int x, int y){
        Queue<Node> queue = new LinkedList<>();
        queue.add(new Node(x,y));
        visited[x][y] = true;

        int count=1;
        while(!queue.isEmpty()){
            Node now = queue.poll();

            for(int i=0; i<4; i++){ // 현재의 집의 상하좌우 확인 후 큐에 저장
                int px = now.x + mx[i];
                int py = now.y + my[i];
                if(px >0 && py>0 && px<=N && py <=N){
                    if(maps[px][py]==1 && !visited[px][py]){
                        count++; // 집 증가
                        visited[px][py] = true; // 집 방문 처리
                        queue.add(new Node(px,py));
                    }
                }
            }
        }
        return count;
    }
}

알고 넘어아기

BFS를 이용해서 풀었다. 입력받은 값을 maps에 저장하고 maps를 반복문으로 돌면서 1을 만나고 방문하지 않은 1이면 BFS를 돌렸다. 돌리는 과정에서 만난 1들을 방문처리를 해줬다. 그렇게 되면 결과적으로 단지의 수만큼 BFS를 돌게된다.

profile
도전하자

0개의 댓글