-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathKahn's Algorithm for Topological Sort.java
More file actions
79 lines (76 loc) · 1.26 KB
/
Kahn's Algorithm for Topological Sort.java
File metadata and controls
79 lines (76 loc) · 1.26 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
68
69
70
71
72
73
74
75
76
77
78
79
import java.util.Scanner;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Vector;
class Kahns_Algo_TopoLogical_Sort
{
int v;
LinkedList<Integer> adj[];
Kahns_Algo_TopoLogical_Sort(int v)
{
this.v=v;
adj=new LinkedList[v];
for(int i=0;i<v;i++)
{
adj[i]=new LinkedList<>();
}
}
void addEdge(int src,int dest)
{
adj[src].add(dest);
}
void topoSort()
{
int inDegree[]=new int[v];
Queue<Integer> q=new LinkedList<>();
for(int i=0;i<v;i++)
{
inDegree[i]=0;
}
for(int i=0;i<v;i++)
{
for(Integer j:adj[i])
{
inDegree[j]++;
}
}
for(int i=0;i<v;i++)
{
if(inDegree[i]==0)
q.add(i);
}
Vector<Integer> output=new Vector<>();
int ct=0;
while(!q.isEmpty())
{
int u=q.poll();
output.add(u);
for(Integer i:adj[u])
{
if(--inDegree[i]==0)
q.add(i);
}
ct++;
}
if(ct!=v)
System.out.println("Graph is not DAG");
else
{
for(Integer i:output)
System.out.print(i+" ");
}
}
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int v=sc.nextInt();
int e=sc.nextInt();
Kahns_Algo_TopoLogical_Sort g=new Kahns_Algo_TopoLogical_Sort(v);
for(int i=1;i<=e;i++)
{
int src=sc.nextInt();
int dest=sc.nextInt();
g.addEdge(src,dest);
}
g.topoSort();
}
}