-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathsolution.java
More file actions
39 lines (34 loc) · 1.1 KB
/
Copy pathsolution.java
File metadata and controls
39 lines (34 loc) · 1.1 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
import java.util.*;
/*
* Java solution using Kahn's algorithm (BFS topological sort).
*/
class Solution {
public ArrayList<Integer> findOrder(int n, int[][] prerequisites) {
ArrayList<ArrayList<Integer>> adj = new ArrayList<>(n);
for (int i = 0; i < n; ++i)
adj.add(new ArrayList<>());
int[] indeg = new int[n];
for (int[] pr : prerequisites) {
int x = pr[0], y = pr[1]; // y -> x
adj.get(y).add(x);
indeg[x]++;
}
Queue<Integer> q = new LinkedList<>();
for (int i = 0; i < n; ++i)
if (indeg[i] == 0)
q.offer(i);
ArrayList<Integer> order = new ArrayList<>(n);
while (!q.isEmpty()) {
int node = q.poll();
order.add(node);
for (int nei : adj.get(node)) {
indeg[nei]--;
if (indeg[nei] == 0)
q.offer(nei);
}
}
if (order.size() == n)
return order;
return new ArrayList<>(); // cycle detected
}
}