forked from fengvyi/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
802. Find Eventual Safe States.cpp
56 lines (52 loc) · 1.6 KB
/
802. 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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
class Solution {
public:
vector<int> eventualSafeNodes(vector<vector<int>>& graph) {
vector<int>res;
int n = graph.size();
vector<int>loop(n), safe(n), visited(n);
for(int i = 0; i < n; i++)
if(isSafe(graph, visited, loop, safe, i)) res.push_back(i);
return res;
}
bool isSafe(vector<vector<int>>& graph, vector<int>& visited, vector<int>& loop, vector<int>& safe, int node){
if(safe[node]) return true;
if(loop[node] || visited[node]) return false;
visited[node] = 1;
bool b = true;
for(int neigh: graph[node]) b &= isSafe(graph, visited, loop, safe, neigh);
visited[node] = 0;
b ? safe[node] = 1 : loop[node] = 1;
return b;
}
};
class Solution {
public:
vector<int> eventualSafeNodes(vector<vector<int>>& graph) {
vector<int>res;
int n = graph.size();
vector<int>dp(n);
vector<int>visited(n);
for (int i = 0; i < n; ++i) {
if (dfs(graph, i, visited, dp)) {
res.push_back(i);
}
}
return res;
}
bool dfs(vector<vector<int>>& graph, int node, vector<int>& visited, vector<int>& dp) {
if (dp[node]) {
return dp[node] == 1 ? true : false;
}
if (visited[node]) {
return false;
}
visited[node] = 1;
bool isValid = true;
for (int x : graph[node]) {
isValid &= dfs(graph, x, visited, dp);
}
visited[node] = 0;
dp[node] = isValid ? 1 : -1;
return isValid;
}
};