baekjoon/Graph_Search

백준 2667번 : 단지번호붙이기 자바

Meluu_ 2024. 1. 16. 21:22

백준 2667번

 

2667번: 단지번호붙이기

<그림 1>과 같이 정사각형 모양의 지도가 있다. 1은 집이 있는 곳을, 0은 집이 없는 곳을 나타낸다. 철수는 이 지도를 가지고 연결된 집의 모임인 단지를 정의하고, 단지에 번호를 붙이려 한다. 여

www.acmicpc.net

 

문제


 

풀이


 

미로 찾기와 매우 유사한 문제이다. 

다른점은 단지라는 그래프의 개수와 각 단지의 집들 즉, 각 그래프의 노드들의 개수를 오름차순으로 출력하는 문제이다. 

 

그저 그래프를 찾아내서 얼마만큼의 노드들이 연결되어 있는지만 확인하기에

BFS, DFS 둘다 사용이 가능하다. 

 

여기서는 BFS를 사용하였다. 

 

 

 

 

import java.io.*;
import java.util.*;

public class Main {

    static int[][] graph;
    static boolean[][] visited;
    static int V,count;

    static int[] UD = {0, 0, -1, 1};
    static int[] LR = {-1, 1, 0, 0};


    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));

        V = Integer.parseInt(br.readLine());

        graph = new int[V][V];
        visited = new boolean[V][V];

        ArrayList<Integer> list = new ArrayList<>();

        // 그래프 초기화
        for (int i = 0; i < V; i++) {
            String line = br.readLine();
            for (int j = 0; j < V; j++) {
                graph[i][j] = line.charAt(j) - '0';
            }
        }

        // 순회하면서 새로운 단지 찾기
        for (int i = 0; i < V; i++) {
            for (int j = 0; j < V; j++) {
                if (!visited[i][j] && graph[i][j] == 1) {
                    list.add(bfs(i, j));
                }
            }
        }

        // 오름차순 정렬
        Collections.sort(list);

        // 출력
        // 단지 총 수
        System.out.println(list.size());

        // 각 단지 내 집의 수
        for (int i = 0; i < list.size(); i++) {
            System.out.println(list.get(i));
        }
    }


    public static int bfs(int x, int y) {
        visited[x][y] = true;
        int count = 1;

        Queue<int[]> queue = new LinkedList<>();
        queue.add(new int[]{x, y});

        while (!queue.isEmpty()) {

            int[] node = queue.poll();
            for (int i = 0; i < 4; i++) {
                int next_x = node[0] + UD[i];
                int next_y = node[1] + LR[i];

                if (next_x < 0 || next_y < 0) {
                    continue;
                }

                if (next_x >= V || next_y >= V) {
                    continue;
                }


                if (!visited[next_x][next_y] && graph[next_x][next_y] == 1) {

                    queue.add(new int[]{next_x, next_y});
                    visited[next_x][next_y] = true;
                    count++;
                }

            }

        }
        return count;
    }


}


/**
 * 우선 그래프 배열에 다 넣고
 * 순회하면서 값이 1 && visited=false 이면 dfs
 * ArrayList에 값 넣어주고 나중에 sort 및 출력
 *
 */