-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathTopSort.java
More file actions
29 lines (24 loc) · 804 Bytes
/
TopSort.java
File metadata and controls
29 lines (24 loc) · 804 Bytes
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
class TopSort {
static int n;
static int[] inEdges;
static ArrayDeque[] edges;
public static void main (String[] args){
inEdges = new int[n];
//while scanning in edges, add 1 to inEdges at connecting node
ArrayDeque<Integer> starts = new ArrayDeque<Integer>();
for(int i = 0; i < n; ++i){
if(inEdges[i] == 0) starts.offer(i);
}
while(!starts.isEmpty()){
ArrayDeque<Integer> newStarts = new ArrayDeque<Integer>();
for(int curr : starts){
for(int next : (ArrayDeque<Integer>) edges[curr]){
--inEdges[next];
if(inEdges[next] == 0) newStarts.offer(next);
}
}
starts.clear();
starts.addAll(newStarts);
}
}
}