-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathTopologicalSort.java
More file actions
67 lines (53 loc) · 1.7 KB
/
TopologicalSort.java
File metadata and controls
67 lines (53 loc) · 1.7 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
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
import java.util.*;
public class TopologicalSort {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int nv = sc.nextInt();
int ne = sc.nextInt();
ArrayList<ArrayList<Integer>> adj = new ArrayList<ArrayList<Integer>>(nv);
for (int i = 0; i < nv; i++)
adj.add(new ArrayList<Integer>());
for (int i = 0; i < ne; i++) {
int firstVertex = sc.nextInt();
int secondVertex = sc.nextInt();
adj.get(firstVertex).add(secondVertex);
// adj.get(secondVertex).add(firstVertex);
}
sc.close();
int[] tsort = topologicalSort(nv, adj);
for (int i : tsort) {
System.out.print(i + " ");
}
}
private static int[] topologicalSort(int nv, ArrayList<ArrayList<Integer>> adj) {
ArrayList<Integer> ans = new ArrayList<>();
int[] inDegree = new int[nv];
for (ArrayList<Integer> list : adj) {
for (Integer i : list) {
inDegree[i]++;
}
}
Queue<Integer> q = new LinkedList<>();
for (int i = 0; i < nv; i++) {
if (inDegree[i] == 0) {
q.add(i);
}
}
while (!q.isEmpty()) {
int cur = q.poll();
ans.add(cur);
for (int neighbour : adj.get(cur)) {
inDegree[neighbour]--;
if (inDegree[neighbour] == 0) {
q.add(neighbour);
}
}
}
int[] topoSort = new int[ans.size()];
int i = 0;
for (int e : ans) {
topoSort[i++] = e;
}
return topoSort;
}
}