코딩 테스트

(Java) 프로그래머스 카카오 프렌즈 컬러링북

로승리 2022. 6. 12. 04:20

전형적인 DFS / BFS 문제였다.

구현은 쉬웠는데 계속 통과가 안돼서 30분을 넘게 봐도 이상한 점을 못 찾았는데

전역 변수 사용 시 메서드 내에서 초기화를 해야 통과한다.


최종 코드

class Solution {
    static int numberOfArea;
    static int maxSizeOfOneArea;
    static int cnt = 0;
    static int[] dx = {1,-1,0,0};
    static int[] dy = {0,0,1,-1};
    
    public int[] solution(int m, int n, int[][] picture) {
        numberOfArea =0;
        maxSizeOfOneArea=0;
        int[] answer = new int[2];
        answer[0] = numberOfArea;
        answer[1] = maxSizeOfOneArea;
        
        boolean[][] check = new boolean[m][n];
        
        for(int i =0;i<m;i++){
            for(int j=0;j<n;j++){
                if(picture[i][j] != 0 && !check[i][j]){
                    numberOfArea++;
                    dfs(i,j,picture,check);
                }
                if(cnt > maxSizeOfOneArea) maxSizeOfOneArea = cnt;
                cnt = 0;
            }
        }
        
        answer[0] = numberOfArea;
        answer[1] = maxSizeOfOneArea;
        
        return answer;
    }
        static void dfs(int x,int y, int[][] picture, boolean[][] check){
        if(check[x][y]) return;
        check[x][y] = true;
        cnt++;
        
        for(int i =0;i<4;i++){
            int nx = x + dx[i];
            int ny = y + dy[i];
            
            if(nx<0 || nx>=picture.length || ny<0 || ny>=picture[0].length) continue;
            
            if(picture[x][y] == picture[nx][ny] && !check[nx][ny]){                
                dfs(nx,ny,picture,check);
            }            
        }        
    }
}