| 1 | fun prerequisites(n: Int, prerequisites: List<List<Int>>): Boolean { |
| 2 | val graph = mutableMapOf<Int, MutableList<Int>>() |
| 3 | val inDegrees = IntArray(n) |
| 4 | // Represent the graph as an adjacency list and record the in- |
| 5 | // degree of each course. |
| 6 | for ((prerequisite, course) in prerequisites) { |
| 7 | graph.getOrPut(prerequisite) { mutableListOf() }.add(course) |
| 8 | inDegrees[course]++ |
| 9 | } |
| 10 | val queue = ArrayDeque<Int>() |
| 11 | // Add all courses with an in-degree of 0 to the queue. |
| 12 | for (i in inDegrees.indices) { |
| 13 | if (inDegrees[i] == 0) { |
| 14 | queue.add(i) |
| 15 | } |
| 16 | } |
| 17 | var enrolledCourses = 0 |
| 18 | // Perform topological sort. |
| 19 | while (queue.isNotEmpty()) { |
| 20 | val node = queue.removeFirst() |
| 21 | enrolledCourses++ |
| 22 | for (neighbor in graph[node] ?: mutableListOf()) { |
| 23 | inDegrees[neighbor]-- |
| 24 | // If the in-degree of a neighboring course becomes 0, add |
| 25 | // it to the queue. |
| 26 | if (inDegrees[neighbor] == 0) { |
| 27 | queue.add(neighbor) |
| 28 | } |
| 29 | } |
| 30 | } |
| 31 | // Return true if we've successfully enrolled in all courses. |
| 32 | return enrolledCourses == n |
| 33 | } |