-
2차원 동전 뒤집기 (with Kotlin)Programmers Practice/level 3 2025. 6. 24. 16:03
https://school.programmers.co.kr/learn/courses/30/lessons/131703
프로그래머스
SW개발자를 위한 평가, 교육의 Total Solution을 제공하는 개발자 성장을 위한 베이스캠프
programmers.co.kr
이 문제는 DFS를 활용해서 모든 경우를 탐색하도록 의도된 문제로 보인다.
시간 복잡도 측면에서는 더 효율적인 풀이가 있을 수도 있지만, 문제의 본래 의도를 따라 푸는 것이 더 바람직하다고 생각한다.import kotlin.math.min var answer: Int? = null fun Array<IntArray>.flip(row: Int) { for (col in this[0].indices) { this[row][col] = this[row][col] xor 1 } } class Solution { fun flatCount(graph: Array<IntArray>, target: Array<IntArray>): Int? { var flatCount = 0 for (col in graph[0].indices) { val matchCount = graph.indices .count { row -> graph[row][col] == target[row][col] } when { matchCount == 0 -> flatCount++ matchCount < graph.size -> return null } } return flatCount } fun dfs(graph: Array<IntArray>, target: Array<IntArray>, level: Int, count: Int) { if (level == graph.size) { flatCount(graph, target)?.let { answer = min(answer ?: Int.MAX_VALUE, count + it) } return } dfs(graph, target, level + 1, count) graph.flip(level) dfs(graph, target, level + 1, count + 1) graph.flip(level) } fun solution(beginning: Array<IntArray>, target: Array<IntArray>): Int { dfs(beginning, target, 0, 0) return answer ?: -1 } }
'Programmers Practice > level 3' 카테고리의 다른 글
선입 선출 스케줄링 (with Kotlin) (0) 2025.07.01 풍선 터트리기 (with Kotlin) (0) 2025.06.26 자물쇠와 열쇠 (with Kotlin) (1) 2025.06.26 홀짝트리 (with Kotlin) (0) 2025.06.24 봉인된 주문 (with Kotlin) (0) 2025.06.24