Skip to content

Instantly share code, notes, and snippets.

@fengyitsai
Created January 14, 2020 13:41
Show Gist options
  • Save fengyitsai/736ee98d6705213ab66ac95ea1ec586e to your computer and use it in GitHub Desktop.
Save fengyitsai/736ee98d6705213ab66ac95ea1ec586e to your computer and use it in GitHub Desktop.
802. Find Eventual Safe States
class Solution {
func eventualSafeNodes(_ graph: [[Int]]) -> [Int] {
var record = [Int:Bool]()
func visit(_ i:Int, _ visited:inout Set<Int>) -> Bool {
if let isSafe = record[i] {
return isSafe
}
if visited.contains(i) {
record[i] = false
return false
}
visited.insert(i)
for neighbor in graph[i] {
if !visit(neighbor, &visited) {
record[i] = false
visited.remove(i)
return false
}
}
visited.remove(i)
record[i] = true
return true
}
var result = [Int]()
for (index, node) in graph.enumerated() {
var visited = Set<Int>()
if visit(index, &visited) {
result.append(index)
}
}
return result
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment