-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
Copy path_802.java
55 lines (53 loc) · 1.93 KB
/
_802.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
44
45
46
47
48
49
50
51
52
53
54
55
package com.fishercoder.solutions.firstthousand;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
public class _802 {
public static class Solution1 {
/*
* This is a variation of the templated topological sort in that it doesn't use indegree array, instead, it uses an outdegree array.
* <p>
* For topological sort, it usually makes sense to just keep an array of elements since it's a graph of n nodes,
* we always need to take care each and every one of the nodes, no skipping any, so using an array could let you access each node by its index/name directly.
*/
public List<Integer> eventualSafeNodes(int[][] graph) {
int n = graph.length;
List<Integer>[] adjList = new ArrayList[n];
for (int i = 0; i < n; i++) {
adjList[i] = new ArrayList<>();
}
int[] outdegree = new int[n];
for (int i = 0; i < n; i++) {
for (int g : graph[i]) {
adjList[g].add(i);
outdegree[i]++;
}
}
Queue<Integer> q = new LinkedList<>();
for (int i = 0; i < n; i++) {
if (outdegree[i] == 0) {
q.offer(i);
}
}
boolean[] safe = new boolean[n];
while (!q.isEmpty()) {
Integer curr = q.poll();
safe[curr] = true;
for (int v : adjList[curr]) {
outdegree[v]--;
if (outdegree[v] == 0) {
q.offer(v);
}
}
}
List<Integer> result = new ArrayList<>();
for (int i = 0; i < n; i++) {
if (safe[i]) {
result.add(i);
}
}
return result;
}
}
}