-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFindEventualSafeStates.java
More file actions
75 lines (66 loc) · 2.05 KB
/
FindEventualSafeStates.java
File metadata and controls
75 lines (66 loc) · 2.05 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
66
67
68
69
70
71
72
73
74
75
package leetcode;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
/**
* FindEventualSafeStates
* https://leetcode-cn.com/problems/find-eventual-safe-states/
* 802. 找到最终的安全状态
* https://leetcode-cn.com/problems/find-eventual-safe-states/solution/3zhuang-tai-di-gui-by-oshdyr-ytai/
* 还可以参考拓扑排序
*
* @author tobin
* @since 2021-08-05
*/
public class FindEventualSafeStates {
public static void main(String[] args) {
int[][] graph = {{1, 2}, {2, 3}, {5}, {0}, {5}, {}, {}};
// int[][] graph = {{1, 2, 3, 4}, {1, 2}, {3, 4}, {0, 4}, {}};
FindEventualSafeStates sol = new FindEventualSafeStates();
List<Integer> res = sol.eventualSafeNodes(graph);
for (Integer v : res) {
System.out.println(v);
}
}
public List<Integer> eventualSafeNodes(int[][] graph) {
int[] isSafe = new int[graph.length];
boolean[] isVisited = new boolean[graph.length];
for (int i = 0; i < graph.length; i++) {
isSafe[i] = 0;
isVisited[i] = false;
}
List<Integer> result = new LinkedList<>();
for (int i = 0; i < graph.length; i++) {
if (dp(graph, isSafe, isVisited, i)) {
result.add(i);
}
}
return result;
}
private boolean dp(int[][] graph,
int[] isSafe, boolean[] isVisited,
int curr) {
if (isSafe[curr] == -1) {
return false;
}
if (isSafe[curr] == 1) {
return true;
}
if (isVisited[curr]) {
isSafe[curr] = -1;
return false;
}
isVisited[curr] = true;
int[] nexts = graph[curr];
for (int next : nexts) {
if (!dp(graph, isSafe, isVisited, next)) {
isVisited[curr] = false;
isSafe[curr] = -1;
return false;
}
}
isVisited[curr] = false;
isSafe[curr] = 1;
return true;
}
}