-
Notifications
You must be signed in to change notification settings - Fork 43
/
Copy pathKahn's Algorithm.java
88 lines (66 loc) · 1.77 KB
/
Kahn's Algorithm.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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
// A Java program to print Topological order using Kahn's Algorithm
import java.util.*;
class Graph {
int V;
List<Integer> adj[];
public Graph(int V)
{
this.V = V;
adj = new ArrayList[V];
for (int i = 0; i < V; i++)
adj[i] = new ArrayList<Integer>();
}
public void addEdge(int u, int v)
{
adj[u].add(v);
}
public void topologicalSort()
{
int indegree[] = new int[V];
for (int i = 0; i < V; i++) {
ArrayList<Integer> temp
= (ArrayList<Integer>)adj[i];
for (int node : temp) {
indegree[node]++;
}
}
Queue<Integer> q
= new LinkedList<Integer>();
for (int i = 0; i < V; i++) {
if (indegree[i] == 0)
q.add(i);
}
int count = 0;
LinkedList<Integer> topological_Order = new LinkedList<Integer>();
while (!q.isEmpty()) {
int u = q.poll();
topological_Order.add(u);
for (int node : adj[u]) {
if (--indegree[node] == 0)
q.add(node);
}
count++;
}
if (count != V) {
System.out.println("There is a cycle in the graph");
return;
}
for (int i : topological_Order) {
System.out.print(i + " ");
}
}
}
class Main {
public static void main(String args[])
{
Graph g = new Graph(6);
g.addEdge(5, 2);
g.addEdge(5, 0);
g.addEdge(4, 0);
g.addEdge(4, 1);
g.addEdge(2, 3);
g.addEdge(3, 1);
System.out.println("Topological Sort :- ");
g.topologicalSort();
}
}