KO EN

[Kotlin] 프로그래머스 - 카카오 프렌즈 컬러링북

by 민갤

Back End /

문제

링크

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

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

제한사항

입력은 그림의 크기를 나타내는 m과 n, 그리고 그림을 나타내는 m × n 크기의 2차원 배열 picture로 주어진다. 제한조건은 아래와 같다.

  • 1 <= m, n <= 100
  • picture의 원소는 0 이상 2^31 - 1 이하의 임의의 값이다.
  • picture의 원소 중 값이 0인 경우는 색칠하지 않는 영역을 뜻한다.

리턴 타입은 원소가 두 개인 정수 배열이다. 그림에 몇 개의 영역이 있는지와 가장 큰 영역은 몇 칸으로 이루어져 있는지를 리턴한다.

입출력 예시

입력

  • m: 6
  • n: 4
  • picture

출력: [4, 5]

풀이

색칠 영역을 구하는 문제이므로 색이 없는 영역인 0은 제외한다.

같은 색이 어디까지 이어져 있는 지 확인하기 위해 그래프 탐색 알고리즘을 활용한다.

중복 확인을 방지하기 위한 배열을 같이 사용한다.

코드. Kotlin

class Solution {
    // 상하좌우 좌표
    private val distanceX = intArrayOf(0, 0, -1, 1)
    private val distanceY = intArrayOf(-1, 1, 0, 0)
    // 방문 여부
    private lateinit var visited: Array<BooleanArray>
    private var count = 0

    private fun solution(m: Int, n: Int, picture: Array<IntArray>): IntArray {
        visited = Array(m) { BooleanArray(n) { false } }

        val color = mutableListOf<Int>()

        for (y in 0 until m) {
            for (x in 0 until n) {
                if (picture[y][x] == 0 || visited[y][x]) continue
                dfs(n, m, x, y, picture[y][x], picture)
                color.add(count)
                count = 0
            }
        }

        color.sort()
        return intArrayOf(color.size, color.last())
    }

    private fun dfs(n: Int, m: Int, x: Int, y: Int, target: Int, picture: Array<IntArray>) {
        visited[y][x] = true
        count++

        for (i in 0..3) {
            val nextY = y + distanceY[i]
            val nextX = x + distanceX[i]

            if (nextY >= m || nextX >= n || nextY < 0 || nextX < 0) continue
            if (visited[nextY][nextX] || picture[nextY][nextX] == 0) continue
            if (target != picture[nextY][nextX]) continue

            dfs(n, m, nextX, nextY, target, picture)
        }
    }
}
Kotlin 제출 없음. 예제 입출력 통과

코드. JAVA

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

class Solution {
    private int[] distanceX = {0, 0, -1, 1};
    private int[] distanceY = {-1, 1, 0, 0};

    private boolean[][] visited;
    private int count = 0;
    
    public int[] solution(int m, int n, int[][] picture) {
        visited = new boolean[m][n];

        List<Integer> color = new ArrayList<>();

        for (int y = 0; y < m; y++) {
            for (int x = 0; x < n; x++) {
                if (picture[y][x] == 0 || visited[y][x]) continue;
                dfs(n, m, x, y, picture[y][x], picture);
                color.add(count);
                count = 0;
            }
        }

        Collections.sort(color, Collections.reverseOrder());
        return new int[]{color.size(), color.get(0)};
    }

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

        for (int i = 0; i < 4; i++) {
            int nextY = y + distanceY[i];
            int nextX = x + distanceX[i];

            if (nextY >= m || nextX >= n || nextY < 0 || nextX < 0) continue;
            if (visited[nextY][nextX] || picture[nextY][nextX] == 0) continue;
            if (target != picture[nextY][nextX]) continue;

            dfs(n, m, nextX, nextY, target, picture);
        }
    }
}
테스트 1 〉	통과 (15.27ms, 94.5MB)

Kotlin 전체 코드 링크

Author

민갤

민갤

Back-End Developer

꾸잉꾸잉하고 웁니다.

로그인

디코에 오신 것을 환영해요!
전문가들의 수많은 아티클 창고 🤓