카카오프렌즈 컬러링북
문제정의
상하좌우 중 한 방향으로라도 같은 색깔이 칠해진 곳을 같은 영역이라 정의할 때, 영역의 개수와 최대 영역 넓이를 반환하는 함수를 만드는 문제이다.
문제풀이
전체 코드는 다음과 같다. 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55public class KaKaoFriendColoringBook {
    
    //프로그래머스 문제풀이 level2 카카오프렌즈 컬러링북
    public static void main(String[] args)
    {
        int m = 6, n = 4;
        int[][] picture = {
            {1,1,1,0},
            {1,2,2,0},
            {1,0,0,1},
            {0,0,0,1},
            {0,0,0,3},
            {0,0,0,3}
        };
        int numberOfArea = 0;
        int maxSizeOfOneArea = 0;
        int[] answer = new int[2];
        boolean[][] visited = new boolean[m][n];
        for(int i = 0; i < m; i++)
        {
            for(int j = 0; j<n; j++)
            {
                if(visited[i][j] == false && picture[i][j] != 0)
                {
                    numberOfArea++;
                    maxSizeOfOneArea = Math.max(maxSizeOfOneArea, getRegion(visited, i, j, picture, 0, picture[i][j], m, n));
                }
            }
        }        
        answer[0] = numberOfArea;
        answer[1] = maxSizeOfOneArea;
    }
    public static int getRegion(boolean[][] visited, int r, int c, int[][] picture, int area, int c_id, int m, int n)
    {
        if(r == m || c == n || r < 0 || c < 0)
            return area;
        if(picture[r][c] != c_id)
            return area;
        else if(visited[r][c] == true)
            return area;
        else
        {
            visited[r][c] = true;
            area++;
            int left = getRegion(visited, r, c-1, picture, 0, c_id, m, n);
            int right = getRegion(visited, r, c+1, picture, 0, c_id, m, n);
            int up = getRegion(visited, r-1, c, picture, 0, c_id, m, n);
            int down = getRegion(visited, r+1, c, picture, 0, c_id, m, n);
            
            return area+left+right+up+down;
        }
    }
}
시간복잡도는 모든 영역이 칠해져 있을 때가 최악의 경우이다. 왜냐하면 mxn영역을 다보는데 mxn번 만큼 함수가 계속 호출되기 때문이다. 따라서 최종 시간복잡도는 \(O((m*n)^2)\)이다.
테스트