forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
0802-find-eventual-safe-states.kt
32 lines (30 loc) · 1.09 KB
/
0802-find-eventual-safe-states.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
class Solution {
fun eventualSafeNodes(graph: Array<IntArray>): List<Int> {
val resultantList = mutableListOf<Int>()
// -1 -> non-safe node, 0 -> unknown, 1-> safe node
val safeState = IntArray(graph.size)
val visitedNode = hashSetOf<Int>()
fun isSafe(currentNode: Int): Boolean {
visitedNode.add(currentNode)
for (adjacentNode in graph[currentNode]) {
if (safeState[adjacentNode] == 1) continue
if (
adjacentNode in visitedNode ||
safeState[adjacentNode] == -1 ||
!isSafe(adjacentNode)
) {
safeState[adjacentNode] = -1
safeState[currentNode] = -1
return false
}
}
safeState[currentNode] = 1
return true
}
for (node in graph.indices) {
if (safeState[node] == -1) continue
if (safeState[node] == 1 || isSafe(node)) resultantList.add(node)
}
return resultantList
}
}