forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
1462-course-schedule-iv.kt
34 lines (32 loc) · 1.4 KB
/
1462-course-schedule-iv.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
class Solution {
fun checkIfPrerequisite(
numCourses: Int,
prerequisites: Array<IntArray>,
queries: Array<IntArray>
): List<Boolean> {
// { course -> [ immediate pre-requisites ] }
val adjacencyList = mutableMapOf<Int, MutableList<Int>>()
prerequisites.forEach { (immediatePrerequisite, course) ->
adjacencyList.getOrPut(course) { mutableListOf() }.add(immediatePrerequisite)
}
// { course -> [ complete set of prerequisites including transitive pre-requisites ] }
val prerequisitesMap = mutableMapOf<Int, HashSet<Int>>()
fun dfs(startCourse: Int, currentCourse: Int = startCourse) {
if (currentCourse in (prerequisitesMap[startCourse] ?: hashSetOf())) return
if (currentCourse != startCourse) {
prerequisitesMap.getOrPut(startCourse) { hashSetOf() }.add(currentCourse)
}
for (immediatePrerequisite in adjacencyList[currentCourse] ?: mutableListOf()) {
dfs(startCourse, immediatePrerequisite)
}
}
for (course in 0 until numCourses) {
dfs(startCourse = course)
}
val resultantList = mutableListOf<Boolean>()
queries.forEach { (prerequisite, course) ->
resultantList.add(prerequisitesMap[course]?.let { prerequisite in it } ?: false)
}
return resultantList
}
}