본문 바로가기
알고리즘/프로그래머스

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

by justkeepgoing 2024. 3. 4.
728x90
반응형

1. 문제

programmers.co.kr/learn/courses/30/lessons/1829

 

코딩테스트 연습 - 카카오프렌즈 컬러링북

6 4 [[1, 1, 1, 0], [1, 2, 2, 0], [1, 0, 0, 1], [0, 0, 0, 1], [0, 0, 0, 3], [0, 0, 0, 3]] [4, 5]

programmers.co.kr

2. 풀이

  • 입력받는 picture배열을 그래도 사용하면 제출 시 틀렸다고 한다
  • picture 배열을 복사하여 풀었다.

3. 코드

class Solution {
     static int[][]dir = {{-1,0},{0,1},{1,0},{0,-1}};
    static int[][] pictures;
    public int[] solution(int m, int n, int[][] picture) {
       int numberOfArea = 0;
        int maxSizeOfOneArea = Integer.MIN_VALUE;
        pictures = new int[m][n];
        for (int i = 0; i < picture.length; i++) {
            for (int j = 0; j < picture[0].length; j++) {
                pictures[i][j] = picture[i][j];
            }
        }
        int size=0;
        for(int i =0; i<m; i++) {
            for(int j =0; j<n;j++) {
                if(pictures[i][j]>0) {
                    size = dfs(i, j, m, n, pictures[i][j]);
                    maxSizeOfOneArea = Math.max(maxSizeOfOneArea, size);
                    numberOfArea++;
                }
            }
        }
        return new int[]{numberOfArea,maxSizeOfOneArea};
    }
    static int dfs(int r, int c, int m, int n, int number){
        int tmp =1;
        if(pictures[r][c] != number) return 0;
        pictures[r][c]=0;
        for(int d=0; d<4; d++) {
            int newR = r +dir[d][0];
            int newC = c +dir[d][1];
            if(isRange(newR,newC,m,n) && pictures[newR][newC]!=0) {
                if(number == pictures[newR][newC]) {
                    tmp+=dfs(newR,newC,m,n,number);
                }
            }
        }
        return tmp;
    }
    static boolean isRange(int r, int c, int m, int n){
        return r>=0 && c>=0 && m>r && n>c;
    }

}

 

반응형

 

반응형