Notice
Recent Posts
Recent Comments
Link
«   2024/07   »
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
Archives
Today
Total
관리 메뉴

csct3434

[level 2] 카카오프렌즈 컬러링북 - 1829 본문

프로그래머스

[level 2] 카카오프렌즈 컬러링북 - 1829

csct3434 2024. 2. 28. 19:38

문제 링크

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

class Solution {

    private static final int[] dx = {0, 0, 1, -1};
    private static final int[] dy = {1, -1, 0, 0};

    private boolean[][] visited = new boolean[100][100];
    private int sizeOfArea;

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

        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (!visited[i][j] && picture[i][j] != 0) {
                    numberOfArea++;
                    sizeOfArea = 0;

                    dfs(i, j, m, n, picture);

                    maxSizeOfOneArea = Math.max(maxSizeOfOneArea, sizeOfArea);
                }
            }
        }

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

    private void dfs(int x, int y, final int m, final int n, final int[][] picture) {
        visited[x][y] = true;
        sizeOfArea++;

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

            if (canGo(nx, ny, m, n, picture, picture[x][y])) {
                dfs(nx, ny, m, n, picture);
            }
        }
    }

    private boolean canGo(int x, int y, int m, int n, int[][] picture, int color) {
        if(!(x >= 0 && x < m && y >= 0 && y < n)) {
            return false;
        }
        return !visited[x][y] && picture[x][y] == color;
    }
}