Algorithm/baekjoon

단지번호 붙이기

마닐라 2022. 2. 18. 22:43

📍 문제 설명

 

💡 접근

전형적인 BFS 문제

 

👩‍💻 코드

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

public class Main {
    static int n, m, v, e, k, answer, cnt;
    static int[][] board;
    static int[] arr;
    static long[] dp;
    static boolean[][] visited;
    static int[] dx = {-1,1,0,0};
    static int[] dy = {0,0,-1,1};
    static ArrayList<Integer> list = new ArrayList<>();
    static StringBuilder sb = new StringBuilder();

    public static void main(String[] args) {
        Scanner kb = new Scanner(System.in);
        Main T = new Main();
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        n = kb.nextInt();
        kb.nextLine();
        board = new int[n][n];
        for(int i = 0; i < n; i++) {
            String[] s = kb.nextLine().split("");
            for(int j = 0; j < s.length; j++) {
                board[i][j] = Integer.parseInt(s[j]);
            }
        }
        visited = new boolean[n][n];

        //모든 정점에 대해서 확인
        for(int i = 0; i < n; i++) {
            for(int j = 0; j < n; j++) {
                cnt = 0;
                if(board[i][j] == 1 && !visited[i][j]) {
                    answer++;
                    T.solution(i, j);
                    list.add(cnt);
                }
            }
        }
        System.out.println(answer);
        Collections.sort(list);
        for(int x : list) System.out.println(x);
    }


    private void solution(int x, int y) {
        Queue<Point> q = new LinkedList<>();
        q.offer(new Point(x, y));
        visited[x][y] = true;
        while(!q.isEmpty()) {
            Point cp = q.poll();

            for(int i = 0; i < 4; i++) {
                int nx = cp.x + dx[i];
                int ny = cp.y + dy[i];
                if(nx<0 || ny<0 || nx>=n || ny>=n) continue;
                if(board[nx][ny] == 1 && !visited[nx][ny]) {
                    board[nx][ny] = answer;
                    visited[nx][ny] = true;
                    q.offer(new Point(nx, ny));
                }
            }
            cnt++;
        }
    }

    private class Point {
        private int x;
        private int y;

        public Point(int x, int y) {
            this.x = x;
            this.y = y;
        }
    }
}

'Algorithm > baekjoon' 카테고리의 다른 글

토마토  (0) 2022.02.19
미로 탐색  (0) 2022.02.19
이분 그래프  (0) 2022.02.18
연결 요소의 개수  (0) 2022.02.18
DFS와 BFS  (0) 2022.02.18