[백준] 1926 그림

장철현·2023년 11월 22일
0

백준

목록 보기
24/80

링크

1926 그림

문제

풀이

전형적인 bfs문제이다.
딱히 어려운 부분이 없다.

코드

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

public class Main {
    public static int[][] matrix;
    public static boolean[][] visited;
    public static int[] dx = new int[]{-1, 0, 1, 0};
    public static int[] dy = new int[]{0, 1, 0, -1};
    public static int count = 0;
    public static int maxArea = 0;

    public static void main(String[] args) throws Exception {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        String[] arr = br.readLine().split(" ");

        int n = Integer.parseInt(arr[0]);
        int m = Integer.parseInt(arr[1]);

        matrix = new int[n][m];
        visited = new boolean[n][m];

        for(int i=0;i<matrix.length;i++){
            arr = br.readLine().split(" ");

            for(int j=0;j<arr.length;j++){
                matrix[i][j] = Integer.parseInt(arr[j]);
            }
        }

        for(int i=0;i<matrix.length;i++){
            for(int j=0;j<matrix[i].length;j++){
                if(matrix[i][j] == 1 && !visited[i][j]){
                    count++;
                    bfs(i, j);
                }
            }
        }

        System.out.println(count);
        System.out.println(maxArea);

    }

    public static void bfs(int x, int y){
        int paintArea = 1;
        Queue<Integer> queue = new LinkedList<>();
        queue.add(x);
        queue.add(y);
        visited[x][y] = true;

        while(!queue.isEmpty()){
            x = queue.poll();
            y = queue.poll();

            for(int i=0;i<4;i++){
                int newX = x + dx[i];
                int newY = y + dy[i];

                if(newX >= 0 && newX < matrix.length && newY >= 0 && newY < matrix[0].length){
                    if(matrix[newX][newY] == 1 && !visited[newX][newY]){
                        queue.add(newX);
                        queue.add(newY);
                        visited[newX][newY] = true;
                        paintArea++;
                    }
                }
            }

        }
        maxArea = Math.max(maxArea, paintArea);
        
    }

}

0개의 댓글