[programmers] 카카오프렌즈 컬러링북

https://school.programmers.co.kr/learn/courses/30/lessons/1829

import java.util.*;

class Solution {
    int numberOfArea = 0, maxSizeOfOneArea = 0, m = 0, n = 0;
    boolean[][] visited;
    int[][] picture;
    int[] dx = new int[]{0,1,0,-1};
    int[] dy = new int[]{-1,0,1,0};

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

        for(int x = 0 ; x < m ; x++){
            for(int y = 0 ; y < n ; y++){
                if(!visited[x][y] && picture[x][y] != 0) fills(x,y);
            }
        }

        return new int[]{numberOfArea, maxSizeOfOneArea};
    }

    void fills(int x, int y){
        numberOfArea++;
        int color = picture[x][y];
        int cnt = 1;
        visited[x][y] = true;

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

        while(!q.isEmpty()){
            int[] temp = q.poll();

            for(int i = 0 ; i < 4 ; i++){
                int nx = temp[0] + dx[i];
                int ny = temp[1] + dy[i];
                if(nx >= 0 && ny >= 0 && nx < m && ny < n && !visited[nx][ny] && picture[nx][ny] == color){
                    visited[nx][ny] = true;
                    cnt++;
                    q.offer(new int[]{nx,ny});
                }
            }
        }
        maxSizeOfOneArea = Math.max(maxSizeOfOneArea,cnt);
    }
}

© 2023 Lee. All rights reserved.