Problem Solving/Programmers

[Level 2] 카카오프렌즈 컬러링북

kmkunk 2022. 4. 7. 10:59
import java.util.*;

class Solution {
    public boolean[][] visited;
    public int[] dx = new int[]{0,0,1,-1};
    public int[] dy = new int[]{1,-1,0,0};
    
    public int[] solution(int m, int n, int[][] picture) {
        visited = new boolean[m][n];
        int[] answer = new int[2];
        
        for(int i=0; i<m; i++) {
            for(int j=0; j<n; j++) {
                if(!visited[i][j] && picture[i][j]>0) {
                    answer[1] = Math.max(bfs(i,j,m,n,picture),answer[1]);
                    answer[0]++;
                }
            }
        }
        
        return answer;
    }
    
    public int bfs(int i, int j, int m, int n, int[][] picture) {
        Queue<int[]> queue = new LinkedList<>();
        queue.add(new int[]{i,j});
        visited[i][j] = true;
        int count = 1;
        
        while(!queue.isEmpty()) {
            int[] a = queue.poll();
            int x = a[1];
            int y= a[0];
            for(int k=0; k<4; k++) {
                int nx = x+dx[k];
                int ny = y+dy[k];
                if(nx>=0 && ny>=0 && nx<n && ny<m && !visited[ny][nx] && picture[ny][nx]==picture[i][j]) {
                    queue.add(new int[]{ny,nx});
                    visited[ny][nx] = true;
                    count++;
                }
            }
        }
        
        return count;
    }
}