-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTopologicalSort.java
72 lines (62 loc) · 1.22 KB
/
TopologicalSort.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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
package hackpack;
import java.util.ArrayDeque;
import java.util.ArrayList;
public class TopologicalSort {
public Node[] ordering;
boolean[] used;
int nodes;
Node[] nodeList;
public TopologicalSort(Node[] list){
nodeList = list;
nodes = list.length;
used = new boolean[nodes];
ordering = new Node[nodes];
}
// Top sort returns num of possible combinations
public int sortTop(){
int currIndex = 0;
int retVal = 1;
int count = 0;
ArrayDeque<Node> queue = new ArrayDeque<Node>();
for(int i = 0; i < nodes; i++){
if(nodeList[i].inDegree == 0){
queue.add(nodeList[i]);
count++;
}
}
while(currIndex < nodes){
if(queue.size() == 0){
return 0;
}
if(queue.size() < 1){
retVal = 2;
}
for(int i = 0; i < count; i++){
Node n = queue.poll();
ordering[currIndex] = n;
currIndex++;
for(Line e: n.edgeList){
e.towards.inDegree--;
if(e.towards.inDegree == 0){
queue.add(e.towards);
}
}
}
}
return retVal;
}
}
class Node{
public int inDegree;
public ArrayList<Line> edgeList;
public Node(){
inDegree = 0;
edgeList = new ArrayList<Line>();
}
}
class Line{
public Node towards;
public Line(Node n){
towards = n;
}
}