-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTopoSort.java
More file actions
59 lines (48 loc) · 1.43 KB
/
Copy pathTopoSort.java
File metadata and controls
59 lines (48 loc) · 1.43 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
package templates;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;
public class TopoSort {
/*************************
* topological sort- using kahn's algorithm
***************************/
static ArrayList<ArrayList<Integer>> adj;
static ArrayList<Integer> tsort;
static int[] indeg;
static Queue<Integer> q;
static InputReader in = new InputReader(System.in);
public static void tsort(int n, int m) {
indeg = new int[n];
tsort = new ArrayList<>();
q = new LinkedList<>();
adj=new ArrayList<>();
for (int i = 0; i < n; i++)
adj.add(new ArrayList<>());
for (int i = 0; i < m; i++) {
int x = in.nextInt() - 1;
int y = in.nextInt() - 1;
adj.get(x).add(y);
indeg[y]++;
}
for (int i = 0; i < n; i++) {
if (indeg[i] == 0)
q.add(i);
}
while (!q.isEmpty()) {
int v = q.poll();
for (int u : adj.get(v)) {
indeg[u]--;
if (indeg[u] == 0)
q.add(u);
}
tsort.add(v);
}
}
// cycle detection for directed (disconnected or connected) graphs
public static boolean isCycle(int n) {
if (tsort == null) {
System.out.println("first call tsort");
}
return tsort.size() < n;
}
}