[프로그래머스] 카카오프렌즈 컬러링북

Chobby·2024년 2월 26일
1

Programmers

목록 보기
337/345

import java.util.*;

class Solution {
    int[][] direction = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
    boolean[][] visited;
    int m, n;
    int[][] picture;

    public int[] solution(int m, int n, int[][] picture) {
        this.m = m;
        this.n = n;
        this.picture = picture;

        visited = new boolean[m][n];

        int areas = 0;
        int maxSize = 0;

        for(int i=0; i<m; i++) {
            for(int j=0; j<n; j++) {
                if(!visited[i][j] && picture[i][j] != 0) {
                    areas++;
                    maxSize = Math.max(maxSize, bfs(i, j, picture[i][j]));
                }
            }
        }

        int[] answer = new int[2];
        answer[0] = areas;
        answer[1] = maxSize;
        return answer;
    }

    int bfs(int x, int y, int color) {
        Queue<Point> queue = new LinkedList<>();
        queue.add(new Point(x, y));

        int sizeOfArea = 0;
        visited[x][y] = true;

        while(!queue.isEmpty()) {
            Point point = queue.poll();
            sizeOfArea++;

            for(int[] dir : direction) {
                int nx = point.x + dir[0];
                int ny = point.y + dir[1];

                if(nx >= 0 && nx < m && ny >= 0 && ny < n) {
                    if(picture[nx][ny] == color && !visited[nx][ny]) {
                        visited[nx][ny] = true;
                        queue.add(new Point(nx, ny));
                    }
                }
            }
        }

        return sizeOfArea;
    }

    class Point {
        int x;
        int y;

        Point(int x, int y) {
            this.x = x;
            this.y = y;
        }
    }
}
profile
내 지식을 공유할 수 있는 대담함

0개의 댓글