-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathsolution.java
43 lines (37 loc) · 1.23 KB
/
solution.java
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
import java.util.*;
class Solution {
public List<Integer> eventualSafeNodes(int[][] graph) {
int n = graph.length;
List<List<Integer>> reversedGraph = new ArrayList<>();
int[] inDegree = new int[n];
// Reverse the graph and calculate in-degree
for (int i = 0; i < n; i++) {
reversedGraph.add(new ArrayList<>());
}
for (int i = 0; i < n; i++) {
for (int neighbor : graph[i]) {
reversedGraph.get(neighbor).add(i);
inDegree[i]++;
}
}
// Find all terminal nodes
Queue<Integer> queue = new LinkedList<>();
for (int i = 0; i < n; i++) {
if (inDegree[i] == 0)
queue.add(i);
}
// Topological sorting to find safe nodes
List<Integer> safeNodes = new ArrayList<>();
while (!queue.isEmpty()) {
int node = queue.poll();
safeNodes.add(node);
for (int neighbor : reversedGraph.get(node)) {
inDegree[neighbor]--;
if (inDegree[neighbor] == 0)
queue.add(neighbor);
}
}
Collections.sort(safeNodes);
return safeNodes;
}
}