Algorithm/프로그래머스

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

hammii 2021. 10. 3. 15:00
728x90
반응형
 

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

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

 

👩🏻‍💻 코드

import java.awt.*;
import java.util.*;

public class Solution {
    static int[] dx = {-1, 0, 1, 0};
    static int[] dy = {0, -1, 0, 1};
    static int[][] map;
    static boolean[][] visited;

    public int[] solution(int m, int n, int[][] picture) {
        int numberOfArea = 0;
        int maxSizeOfOneArea = 0;
        map = picture;
        visited = new boolean[m][n];

        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (!visited[i][j] && map[i][j] != 0) {
                    numberOfArea++;
                    maxSizeOfOneArea = Math.max(bfs(i, j, m, n), maxSizeOfOneArea);
                }
            }
        }

        int[] answer = new int[2];
        answer[0] = numberOfArea;
        answer[1] = maxSizeOfOneArea;
        return answer;
    }

    public static int bfs(int x, int y, int m, int n) {
        Queue<Point> q = new LinkedList<Point>();
        q.add(new Point(x, y));
        visited[x][y] = true;
        int cnt = 0;

        while (!q.isEmpty()) {
            Point cur = q.poll();
            cnt++;

            for (int i = 0; i < 4; i++) {
                int nx = cur.x + dx[i];
                int ny = cur.y + dy[i];

                if (nx >= 0 && nx < m && ny >= 0 && ny < n) {
                    if (map[nx][ny] == map[x][y] && !visited[nx][ny]) {
                        visited[nx][ny] = true;
                        q.add(new Point(nx, ny));
                    }
                }
            }
        }

        return cnt;
    }
}

 

📝 정리

python은 지원하지 않는 문제여서 java로 풀었다.

항상 하는 BFS 방식으로 각 구역의 넓이를 구한 후, 이 넓이의 최댓값을 maxSizeOfOneArea에 저장해줬다.

 

오랜만에 java로 푸니까 시간이 평소보다는 조금 오래걸렸지만, 코드는 python보다 깔끔한 느낌 ~

 

 

 

728x90
반응형