-
Notifications
You must be signed in to change notification settings - Fork 0
/
802. Find Eventual Safe States
41 lines (40 loc) · 1.19 KB
/
802. Find Eventual Safe States
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
class Solution {
public boolean dfs(List<List<Integer>> adj, int src, boolean[] vis, boolean[] recst) {
vis[src] = true;
recst[src] = true;
for (int x : adj.get(src)) {
if (!vis[x] && dfs(adj, x, vis, recst)) {
return true;
} else if (recst[x]) {
return true;
}
}
recst[src] = false;
return false;
}
public List<Integer> eventualSafeNodes(int[][] graph) {
int n = graph.length;
List<List<Integer>> adj = new ArrayList<>();
for (int i = 0; i < n; i++) {
List<Integer> list = new ArrayList<>();
for (int j = 0; j < graph[i].length; j++) {
list.add(graph[i][j]);
}
adj.add(list);
}
boolean[] vis = new boolean[n];
boolean[] recst = new boolean[n];
for (int i = 0; i < n; i++) {
if (!vis[i]) {
dfs(adj, i, vis, recst);
}
}
List<Integer> ans = new ArrayList<>();
for (int i = 0; i < recst.length; i++) {
if (!recst[i]) {
ans.add(i);
}
}
return ans;
}
}