백준 - 2667번(단지번호붙이기)

최지홍·2022년 2월 12일
0

백준

목록 보기
52/145

문제 출처: https://www.acmicpc.net/problem/2667


문제

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


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;

public class Main {

    private static int[][] directions = {
            { -1, 0 }, // 상
            { 1, 0 },  // 하
            { 0, -1 }, // 좌
            { 0, 1 },  // 우
    };

    private static int count = 1;

    public static void main(String[] args) throws IOException {
        StringBuilder sb = new StringBuilder();
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        int N = Integer.parseInt(reader.readLine());
        int[][] arr = new int[N][N];
        int groupCount = 0;
        ArrayList<Integer> list = new ArrayList<>();

        for (int i = 0; i < N; i++) {
            String[] temp = reader.readLine().split("");
            for (int j = 0; j < N; j++) {
                arr[i][j] = Integer.parseInt(temp[j]);
            }
        }

        for (int i = 0; i < arr.length; i++) {
            for (int j = 0; j < arr.length; j++) {
                if (arr[i][j] == 1) {
                    groupCount++;
                    arr[i][j] = 0;
                    dfs(arr, i, j);
                    list.add(count);
                    count = 1;
                }
            }
        }

        sb.append(groupCount).append("\n");
        Collections.sort(list);
        for (int i = 0; i < list.size(); i++) {
            sb.append(list.get(i)).append("\n");
        }

        System.out.println(sb);
    }

    private static void dfs(int[][] arr, int x, int y) {
        for (int i = 0; i < 4; i++) {
            int dx = x + directions[i][0];
            int dy = y + directions[i][1];

            if (dx >= 0 && dx < arr.length && dy >= 0 && dy < arr.length) {
                if (arr[dx][dy] == 1) {
                    count++;
                    arr[dx][dy] = 0;
                    dfs(arr, dx, dy);
                }
            }
        }
    }

    /*private static int bfs(int[][] arr, int[] startPoint) {
        Queue<int[]> queue = new ArrayDeque<>(); // 배열로 표현된 좌표를 담는 큐
        queue.offer(startPoint);

        int count = 1;

        while (!queue.isEmpty()) {
            int[] point = queue.poll();

            for (int i = 0; i < 4; i++) {
                int dx = point[0] + directions[i][0];
                int dy = point[1] + directions[i][1];

                // 유효범위일 경우
                if (dx >= 0 && dx < arr.length && dy >= 0 && dy < arr.length) {
                    if (arr[dx][dy] == 1) {
                        count++;
                        arr[dx][dy] = 0;
                        queue.offer(new int[] { dx, dy });
                    }
                }
            }
        }

        return count;
    }*/

}

  • 탐색을 연습할 겸 DFS, BFS 두 가지 방법 모두로 풀어보았다.
  • 두 방법 모두 시간은 같게 나왔다.
  • 확실히 구현은 DFS가 간단한 것 같다.
  • 아직 재귀함수가 익숙치 않아 반환값을 다루는 기술이 부족한 것 같다.
profile
백엔드 개발자가 되자!

0개의 댓글