[99클럽 코테 스터디 18일차 TIL] 백준 - 단지번호붙이기

99클럽 코테 스터디 18일차 TIL 입니다.

[Silver I] 단지번호붙이기 - 2667

문제 링크

분류

너비 우선 탐색, 깊이 우선 탐색, 그래프 이론, 그래프 탐색

문제 설명

<그림 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.Arrays;
import java.util.LinkedList;
import java.util.Queue;

public class Main {

    static int n;
    static int[][] map; // 지도
    static boolean[][] visited; // 방문 유무
    static int[] dx = {0, 1, 0, -1}; // 좌하우상
    static int[] dy = {-1, 0, 1, 0}; // 좌하우상
    static int apt = 0; // 단지 수
    static int[] apts; // 단지 최대 개수

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringBuilder sb = new StringBuilder();
        n = Integer.parseInt(br.readLine());
        map = new int[n][n];
        visited = new boolean[n][n];
        apts = new int[n*n];

        // 지도 받기
        for (int i = 0; i < n; i++) {
            String[] p = br.readLine().split("");
            for (int j = 0; j < n; j++) {
                map[i][j] = Integer.parseInt(p[j]);
            }
        }

        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                if (map[i][j] == 1 && !visited[i][j]) {
                    apt++;
                    bfs(i, j);
                }
            }
        }

        Arrays.sort(apts);
        sb.append(apt).append("\n");
        for (int a : apts) {
            if (a != 0) {
                sb.append(a).append("\n");
            }
        }
        System.out.println(sb);
    }

    static void bfs(int x, int y) {
        Queue<int[]> queue = new LinkedList<>();
        queue.add(new int[]{x, y});
        visited[x][y] = true;
        apts[apt]++;
        while (!queue.isEmpty()) {
            int[] cur = queue.poll();
            int currX = cur[0];
            int currY = cur[1];
            for (int i = 0; i < 4; i++) {
                int nx = currX + dx[i];
                int ny = currY + dy[i];
                if (nx < 0 || nx >= n || ny < 0 || ny >= n) continue;
                if (map[nx][ny] != 1 || visited[nx][ny]) continue;
                visited[nx][ny] = true;
                queue.add(new int[]{nx, ny});
                apts[apt]++;
            }
        }
    }
}
  • Time: 108 ms

  • Memory: 14524 KB

문제를 보자마자 BFS 를 생각해서 BFS 로 문제를 풀어봤다. 시간 안에 못 풀어서 페어 프로그래밍을 통해 조언을 듣고 풀 수 있었다. 못 푼 이유는 BFS 함수에서 if (map[nx][ny] != 1 || visited[nx][ny]) continue; 이 조건문을 or 조건이 아닌 and 조건으로 해서 Queue 에 들어가면 안되는 건들이 계속 추가되는 바람에 메모리 초과가 발생했었다. 어이가 없다.

위 코드를 페어 프로그래밍을 통해 조금 더 깔끔하게 개선해봤다.

개선하기

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

public class Main {

    static int n;
    static int[][] map; // 지도
    static int[][] dxy = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}}; // 상하좌우

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringBuilder sb = new StringBuilder();
        n = Integer.parseInt(br.readLine());
        map = new int[n][n];
        List<Integer> complex = new ArrayList<>();

        // 지도 받기
        for (int i = 0; i < n; i++) {
            String[] p = br.readLine().split("");
            for (int j = 0; j < n; j++) {
                map[i][j] = Integer.parseInt(p[j]);
            }
        }

        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                if (map[i][j] == 1) {
                    complex.add(bfs(i, j));
                }
            }
        }

        sb.append(complex.size()).append("\n");
        complex.stream().sorted().forEach(i -> sb.append(i).append("\n"));
        System.out.println(sb);
    }

    static int bfs(int x, int y) {
        Queue<int[]> queue = new LinkedList<>();
        queue.add(new int[]{x, y});
        map[x][y] = 0;
        int cnt = 1;
        while (!queue.isEmpty()) {
            int[] cur = queue.poll();
            int currX = cur[0];
            int currY = cur[1];
            for (int i = 0; i < 4; i++) {
                int nx = currX + dxy[i][0];
                int ny = currY + dxy[i][1];
                if (nx < 0 || nx >= n || ny < 0 || ny >= n) continue;
                if (map[nx][ny] != 1) continue;
                cnt++;
                queue.add(new int[]{nx, ny});
                map[nx][ny] = 0;
            }
        }
        return cnt;
    }
}
  • Time: 112 ms

  • Memory: 14580 KB

stream API 를 써서 속도는 조금 떨어지긴 했는데 가독성이 좀 더 좋아진 것 같다.

DFS 풀이

추후 추가 예정


돌아보기

이번 문제를 풀면서 BFS 에 대해서는 조금 더 익숙해진 것 같다. 그리고 페어 프로그래밍을 통해 다른 분들의 생각이나 코드를 볼 수 있었어서 재밌었다.

다음에는

  • 조건을... 잘 생각하기

  • 주석으로 로직 설명 작성하기


#99클럽 #코딩테스트준비 #개발자취업 #항해99 #TIL

Last updated