-
홀짝트리 (with Kotlin)Programmers Practice/level 3 2025. 6. 24. 18:08
https://school.programmers.co.kr/learn/courses/30/lessons/388354
프로그래머스
SW개발자를 위한 평가, 교육의 Total Solution을 제공하는 개발자 성장을 위한 베이스캠프
programmers.co.kr
apply 메서드를 이용해서 graph, queue를 생성과 동시에 초기화했다.
const val MAX = 1_000_001 var answer: IntArray = intArrayOf(0, 0) class Solution { fun solution(nodes: IntArray, edges: Array<IntArray>): IntArray { val graph = Array(MAX) { mutableListOf<Int>() }.apply { edges.forEach { (a, b) -> get(a).add(b) get(b).add(a) } } val visited = BooleanArray(MAX) { false } for (node in nodes) { if (visited[node]) continue val queue = ArrayDeque<Int>().apply { addLast(node) } var (case1, case2) = 0 to 0 while (queue.isNotEmpty()) { val currentNode = queue.removeFirst() visited[currentNode] = true val flag = (currentNode % 2) xor (graph[currentNode].size % 2) when(flag) { 0 -> case1++ 1 -> case2++ } graph[currentNode] .filterNot { visited[it] } .forEach { nextNode -> queue.addLast(nextNode) } } if (case1 == 1) answer[0]++ if (case2 == 1) answer[1]++ } return answer } }
'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 2차원 동전 뒤집기 (with Kotlin) (1) 2025.06.24