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

2020. 4. 4. 14:22프로그래머스/카카오

import java.util.*;

class Solution {
     int[][] board = new int[101][101];
     boolean[][] visited = new boolean[101][101];
     ArrayList<Integer> sol = new ArrayList<>();
     int[] dx = {1,0,-1,0};
     int[] dy = {0,1,0,-1};

     int result;
    
  class pa{
      int a;
      int b;
      
      pa(int a,int b){
          this.a = a;
          this.b = b;
      }
  }
    
  public int[] solution(int m, int n, int[][] picture) {
      int numberOfArea = 0;
      int maxSizeOfOneArea = 0;
      int da =0;
      for(int i=0; i<m; i++){
          for(int j=0; j<n; j++){
              board[i][j] = picture[i][j];
          }
      }
      
      for(int i=0; i<m; i++){
          for(int j=0; j<n; j++){
              if(visited[i][j]==false && picture[i][j]!=0){
                  da++;
                  bfs(i,j,m,n);
              }
          }
      }
      
      Collections.sort(sol);
      
      int[] answer = new int[2];
      answer[0] = da;
      answer[1] = sol.get(sol.size()-1);
      return answer;
  }
    
    private void bfs(int a,int b,int m,int n){
        result = 1;
        Queue<pa> q = new LinkedList<>();
        
        q.add(new pa(a,b));
        visited[a][b] =true;
        
        while(!q.isEmpty()){
            int x = q.peek().a;
            int y = q.peek().b;
            
            q.remove();
            
            for(int dir=0; dir<4; dir++){
                int nx = x + dx[dir];
                int ny = y + dy[dir];
                
                if(nx <0 || nx>=m || ny<0 || ny>=n){
                    continue;
                }
                if(board[nx][ny]!=board[x][y] || visited[nx][ny]==true){
                    continue;
                }
                else{
                    visited[nx][ny] = true;
                    q.add(new pa(nx,ny));
                    result++;
                }
            }
        }
        sol.add(result);
    }
}

 BFS를 통해 풀었다.