forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
find-eventual-safe-states.cpp
38 lines (35 loc) · 1012 Bytes
/
find-eventual-safe-states.cpp
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
// Time: O(|V| + |E|)
// Space: O(|V|)
class Solution {
public:
enum Color { WHITE, GRAY, BLACK };
vector<int> eventualSafeNodes(vector<vector<int>>& graph) {
vector<int> result;
unordered_map<int, Color> lookup;
for (int i = 0; i < graph.size(); ++i) {
if (dfs(graph, i, &lookup)) {
result.emplace_back(i);
}
}
return result;
}
private:
bool dfs(const vector<vector<int>>& graph, int node,
unordered_map<int, Color> *lookup) {
if ((*lookup)[node] != WHITE) {
return (*lookup)[node] == BLACK;
}
(*lookup)[node] = GRAY;
for (const auto& child : graph[node]) {
if ((*lookup)[child] == BLACK) {
continue;
}
if ((*lookup)[child] == GRAY ||
!dfs(graph, child, lookup)) {
return false;
}
}
(*lookup)[node] = BLACK;
return true;
}
};