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
| class Solution { public List<Integer> eventualSafeNodes(int[][] graph) { int n = graph.length; int[] st = new int[n]; List<Integer> result = new ArrayList<>(); for (int i = 0; i < n; i++) { if (dfs(i, graph, st)) { result.add(i); } } return result; }
public boolean dfs(int cur, int[][] graph, int[] st) { if (st[cur] == 1) { return false; } if (st[cur] == 2) { return true; } st[cur] = 1; for (int k : graph[cur]) { if (st[k] == 2) { continue; } if (st[k] == 1) { return false; } if (!dfs(k, graph, st)) { return false; } } st[cur] = 2; return true; } }
|