|
| 1 | +package leetcode_study |
| 2 | + |
| 3 | +import io.kotest.matchers.shouldBe |
| 4 | +import org.junit.jupiter.api.Test |
| 5 | + |
| 6 | +class `course-schedule` { |
| 7 | + |
| 8 | + /** |
| 9 | + * TC: O(node + edge), SC: O(node + edge) |
| 10 | + */ |
| 11 | + fun canFinish(numCourses: Int, prerequisites: Array<IntArray>): Boolean { |
| 12 | + if (prerequisites.isEmpty()) return true |
| 13 | + |
| 14 | + return usingTopologySort(numCourses, prerequisites) |
| 15 | + } |
| 16 | + |
| 17 | + private fun usingTopologySort(numCourses: Int, prerequisites: Array<IntArray>): Boolean { |
| 18 | + val adj = List(numCourses) { mutableListOf<Int>() } |
| 19 | + val degree = IntArray(numCourses) |
| 20 | + for (e in prerequisites) { |
| 21 | + val (course, pre) = e[0] to e[1] |
| 22 | + adj[pre].add(course) |
| 23 | + degree[course]++ |
| 24 | + } |
| 25 | + |
| 26 | + val queue = ArrayDeque<Int>().apply { |
| 27 | + degree.forEachIndexed { index, i -> |
| 28 | + if (i == 0) { |
| 29 | + this.add(index) |
| 30 | + } |
| 31 | + } |
| 32 | + } |
| 33 | + |
| 34 | + var answer = 0 |
| 35 | + while (queue.isNotEmpty()) { |
| 36 | + val now = queue.removeFirst() |
| 37 | + answer++ |
| 38 | + |
| 39 | + queue.addAll(adj[now].filter { --degree[it] == 0 }) |
| 40 | + } |
| 41 | + |
| 42 | + return answer == numCourses |
| 43 | + } |
| 44 | + |
| 45 | + @Test |
| 46 | + fun `์ฝ์ค์ ๊ฐ์์ ์ฝ์ค ๊ฐ ์์กด์ฑ์ ์ ๋ฌํ๋ฉด ์ฝ์ค๋ฅผ ์๋ฃํ ์ ์๋์ง ์ฌ๋ถ๋ฅผ ๋ฐํํ๋ค`() { |
| 47 | + canFinish(5, |
| 48 | + arrayOf( |
| 49 | + intArrayOf(0,1), |
| 50 | + intArrayOf(0,2), |
| 51 | + intArrayOf(1,3), |
| 52 | + intArrayOf(1,4), |
| 53 | + intArrayOf(3,4) |
| 54 | + ) |
| 55 | + ) shouldBe true |
| 56 | + canFinish(5, |
| 57 | + arrayOf( |
| 58 | + intArrayOf(1,4), |
| 59 | + intArrayOf(2,4), |
| 60 | + intArrayOf(3,1), |
| 61 | + intArrayOf(3,2) |
| 62 | + ) |
| 63 | + ) shouldBe true |
| 64 | + canFinish(2, arrayOf(intArrayOf(1, 0))) shouldBe true |
| 65 | + canFinish(2, arrayOf(intArrayOf(1, 0), intArrayOf(0, 1))) shouldBe false |
| 66 | + canFinish(20, |
| 67 | + arrayOf( |
| 68 | + intArrayOf(0,10), |
| 69 | + intArrayOf(3,18), |
| 70 | + intArrayOf(5,5), |
| 71 | + intArrayOf(6,11), |
| 72 | + intArrayOf(11,14), |
| 73 | + intArrayOf(13,1), |
| 74 | + intArrayOf(15,1), |
| 75 | + intArrayOf(17,4) |
| 76 | + ) |
| 77 | + ) shouldBe false |
| 78 | + } |
| 79 | +} |
0 commit comments