Created
January 14, 2020 13:41
-
-
Save fengyitsai/736ee98d6705213ab66ac95ea1ec586e to your computer and use it in GitHub Desktop.
802. Find Eventual Safe States
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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