-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path01-10-23-FindEventualSafeStates.cpp
More file actions
65 lines (53 loc) · 1.71 KB
/
01-10-23-FindEventualSafeStates.cpp
File metadata and controls
65 lines (53 loc) · 1.71 KB
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
/*
Time O(V + E + nlogn) -> O(nlogn)
Space O(V)
https://leetcode.com/problems/find-eventual-safe-states/description/
*/
class Solution {
#define VISITED 1
#define UNVISITED -1
#define SAFENODE 0
public:
vector<int> eventualSafeNodes(vector<vector<int>>& graph) {
vector<int> visiteds(graph.size(), UNVISITED);
vector<int> ans;
for (int i = 0; i < graph.size(); i++) {
if (graph[i].size() == 0) {
visiteds[i] = SAFENODE;
ans.push_back(i);
}
}
for (int i = 0; i < graph.size(); i++) {
if (visiteds[i] == UNVISITED) {
dfsSafeNode(graph, i, visiteds, ans);
}
}
sort(ans.begin(), ans.end());
return ans;
}
bool dfsSafeNode(vector<vector<int>>& graph, int currentNode,
vector<int>& visiteds, vector<int>& ans) {
if (visiteds[currentNode] == SAFENODE) { // currentNode -> safeNode
return true;
}
visiteds[currentNode] = VISITED;
bool isThisSafeNode = true;
for (int i = 0; i < graph[currentNode].size(); i++) {
if (visiteds[graph[currentNode][i]] == UNVISITED) {
isThisSafeNode =
dfsSafeNode(graph, graph[currentNode][i], visiteds, ans);
} else if (visiteds[graph[currentNode][i]] == VISITED) {
isThisSafeNode = false;
}
if (isThisSafeNode == false) {
break;
}
}
if (isThisSafeNode) {
ans.push_back(currentNode);
visiteds[currentNode] = SAFENODE;
return true;
}
return false;
}
};