-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathCourseScheduleIV1462.kt
51 lines (44 loc) · 1.41 KB
/
CourseScheduleIV1462.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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
package medium
import javax.print.attribute.standard.Destination
object CourseScheduleIV1462 {
fun checkIfPrerequisite(numCourses: Int, prerequisites: Array<IntArray>, queries: Array<IntArray>): List<Boolean> {
val adjList = HashMap<Int, MutableList<Int>>()
for (edge in prerequisites) {
val current = adjList.getOrDefault(edge[0], mutableListOf<Int>())
current.add(edge[1])
adjList[edge[0]] = current
}
val result = mutableListOf<Boolean>()
for (query in queries) {
// Reset the visited array each query
val visited = BooleanArray(numCourses)
result.add(
isPrerequisite(
adjList,
visited,
query[0],
query[1]
)
)
}
return result
}
private fun isPrerequisite(
adjList: HashMap<Int, MutableList<Int>>,
visited: BooleanArray,
src: Int,
target: Int
): Boolean {
visited[src] = true
if (src == target)
return true
var answer = false
val neighbors = adjList.getOrDefault(src, mutableListOf<Int>())
for (adj in neighbors) {
if (visited[adj].not()) {
answer = answer || isPrerequisite(adjList, visited, adj, target)
}
}
return answer
}
}