ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 백준 2667번 단지번호 붙이기 - BFS
    코딩테스트 2021. 6. 16. 13:35

    문제

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

    입력

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

    출력

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

    예제 입력 1 복사

    7 0110100 0110101 1110101 0000111 0100000 0111110 0111000

    예제 출력 1 복사

    3 7 8 9

    출처

    Olympiad > 한국정보올림피아드 > KOI 1996 > 초등부 1번


    풀이 : 이 문제도 전형적인 bfs, dfs 문제이다.

    저번에 풀었던 것처럼 일단 2차원 배열 map을 통해 사각형을 만든 후 입력값과 같도록 각 자리에 0이나 1을 넣어준다. 그 후 map[0][0]부터 for문을 돌면서 1이 나오는 자리를 찾고 그 자리에서부터 bfs를 실행해주면 된다.

    bfs가 실행된 횟수가 단지의 수이고, bfs 함수를 실행하면서 집의 수를 세어 ArrayList에 저장한 후 sort를 통해 정렬하여 출력하면 된다.

     

    주의해야 할 점 : 입력값이 띄어쓰기 없이 들어오므로 stringTokenizer를 사용하지말고, charAt을 사용해 받아와야 한다.

     

    import java.io.BufferedReader;
    import java.io.InputStreamReader;
    import java.util.*;
    
    public class Test {
        static int[][] map;
        static boolean[][] visited;
        static ArrayList<Integer> houseCount;
        static int[] dx = {-1, 1, 0, 0};
        static int[] dy = {0, 0, -1, 1};
        static int n;
        public static void main(String args[]) throws Exception{
            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
            n = Integer.parseInt(br.readLine());
            map = new int[n][n];
            visited = new boolean[n][n];
    
            for (int i = 0; i < n; i++) {
                String str = br.readLine();
                for (int j = 0; j < n; j++) {
                    //띄어쓰기 없이 입력이 들어오므로 charAt 사용
                    map[i][j] = str.charAt(j) - '0'; //-'0'은 char를 int형으로 변환
                }
            }
            int areaCount = 0;
            houseCount = new ArrayList<>();
            for (int i = 0; i < n; i++) {
                for (int j = 0; j < n; j++) {
                    if (map[i][j] == 1 && !visited[i][j]) {
                        areaCount++;
                        bfs(i, j);
                    }
                }
            }
            System.out.println(areaCount);
            Collections.sort(houseCount);
            for (int i = 0; i < houseCount.size(); i++) {
                System.out.println(houseCount.get(i));
            }
        }
    
        static void bfs(int x, int y) {
            int count = 0;
            Queue<Node> queue = new LinkedList<>();
            queue.add(new Node(x, y));
            visited[x][y] = true;
            while (!queue.isEmpty()) {
                Node node = queue.poll();
                count++;
                for (int i = 0; i < 4; i++) {
                    int nx = node.x + dx[i];
                    int ny = node.y + dy[i];
                    if (nx < n && ny < n && nx >= 0 && ny >= 0) {
                        if (!visited[nx][ny] && map[nx][ny] == 1) {
                            visited[nx][ny] = true;
                            queue.add(new Node(nx, ny));
                        }
                    }
                }
            }
            houseCount.add(count);
        }
    
    }
    
    class Node {
        int x;
        int y;
        Node(int x, int y) {
            this.x = x;
            this.y = y;
        }
    
    }
Designed by Tistory.