hong's android

[코딩 테스트] 카카오 프렌즈 컬러링북 본문

Coding-test/Programmers

[코딩 테스트] 카카오 프렌즈 컬러링북

_hong 2023. 1. 1. 19:53

문제

출판사의 편집자인 어피치는 네오에게 컬러링북에 들어갈 원화를 그려달라고 부탁하여 여러 장의 그림을 받았다. 여러 장의 그림을 난이도 순으로 컬러링북에 넣고 싶었던 어피치는 영역이 많으면 색칠하기가 까다로워 어려워진다는 사실을 발견하고 그림의 난이도를 영역의 수로 정의하였다. (영역이란 상하좌우로 연결된 같은 색상의 공간을 의미한다.)

그림에 몇 개의 영역이 있는지와 가장 큰 영역의 넓이는 얼마인지 계산하는 프로그램을 작성해보자.

 

테스트 케이스는 모두 통과하는데 틀렸다고 나온다. 다시 시도해봐야함.

 

풀이

 

import java.util.*;

class Solution {
    public static int[][] arr;
    public static boolean[][] visit;
    public static int M,N;
    public static int[] dx = {1,-1,0,0};
    public static int[] dy = {0,0,1,-1};
    public static int maxSizeOfOneArea, numberOfArea, count;
    public int[] solution(int m, int n, int[][] picture) {
        int[] answer = new int[2];
        M=m;
        N=n;
        maxSizeOfOneArea = Integer.MIN_VALUE;
        numberOfArea = 0;
        count = 0;
        arr = new int[M][N];
        visit = new boolean[M][N];

        for(int i=0; i<m; i++){
            for(int j=0; j<n; j++){
                arr[i][j] = picture[i][j];
            }
        }

        for(int i=0; i<m; i++){
            for(int j=0; j<n; j++){
                if(!visit[i][j] && arr[i][j]!=0){
                    numberOfArea++;
                    count =0;
                    dfs(i,j);
                }
            }
            maxSizeOfOneArea = Math.max(maxSizeOfOneArea,count);
        }
        answer[0] = numberOfArea;
        answer[1] = maxSizeOfOneArea;
        return answer;
    }
    public static void dfs(int r, int c){
        visit[r][c] = true;
        int color = arr[r][c];
        count++;

        for(int i=0; i<4; i++){
            int nx = r+dx[i];
            int ny = c+dy[i];
            if(nx>=0 && ny>=0 && nx<M && ny<N ){
                if(!visit[nx][ny] && arr[nx][ny]!=0 && color == arr[nx][ny]){
                    dfs(nx,ny);
                }
            }
        }
    }
}

https://school.programmers.co.kr/learn/courses/30/lessons/1829#

 

프로그래머스

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

programmers.co.kr