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;
    }
}

'Problem Solving > Programmers' 카테고리의 다른 글

[Level 2] 이진 변환 반복하기  (0) 2022.04.07
[Level 2] 게임 맵 최단거리  (0) 2022.04.07
[Level 2] 모음 사전  (0) 2022.04.06
[Level 2] 교점에 별 만들기  (0) 2022.04.06
[Level 2] 구명보트  (0) 2022.04.06