forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
0207-course-schedule.kt
39 lines (30 loc) · 1009 Bytes
/
0207-course-schedule.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
class Solution {
fun canFinish(numCourses: Int, prerequisites: Array<IntArray>): Boolean {
if (prerequisites.isEmpty()) return true
val nodes = mutableMapOf<Int, MutableList<Int>>()
prerequisites.forEach {
val (v, w) = it
nodes.getOrPut(v) { mutableListOf<Int>() } += w
}
val visited = mutableSetOf<Int>()
val visitedInCurrentStack = mutableSetOf<Int>()
var hasCycle = false
fun traverse(startNode: Int) {
visited.add(startNode)
visitedInCurrentStack.add(startNode)
for (v in nodes[startNode].orEmpty()) {
if (!visited.contains(v)) {
traverse(v)
} else if (visitedInCurrentStack.contains(v)) {
hasCycle = true
return
}
}
visitedInCurrentStack.remove(startNode)
}
for (key in nodes.keys) {
traverse(key)
}
return !hasCycle
}
}