Skip to content

Commit e5db336

Browse files
committed
Added Kahn's Algorithm in python
1 parent 20e9877 commit e5db336

File tree

1 file changed

+88
-0
lines changed

1 file changed

+88
-0
lines changed
Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
1+
2+
from collections import defaultdict
3+
4+
#Class to represent a graph
5+
class Graph:
6+
def __init__(self,vertices):
7+
self.graph = defaultdict(list) #dictionary containing adjacency List
8+
self.V = vertices #No. of vertices
9+
10+
# function to add an edge to graph
11+
def addEdge(self,u,v):
12+
self.graph[u].append(v)
13+
14+
def topological_sort(self):
15+
16+
#initialise in_degrees
17+
in_degree = [0 for i in range(self.V)]
18+
19+
#calculate in_degrees of all vertices
20+
for i in self.graph:
21+
for j in self.graph[i]:
22+
in_degree[j]+=1
23+
24+
#queue to keep track of vertices with 0 in_degree. These will be first in our topological ordering
25+
queue = []
26+
for i in range(self.V):
27+
if(in_degree[i] == 0):
28+
queue.append(i)
29+
30+
31+
#list for our topological ordering
32+
top_order = []
33+
34+
# keep track of visited vertices to ensure there is no cycle
35+
cnt = 0
36+
37+
38+
#run loop until all vertices are added
39+
while queue:
40+
u = queue.pop(0)
41+
top_order.append(u)
42+
43+
#remove edges outgoing from u
44+
for vertex in self.graph[u]:
45+
in_degree[vertex] -= 1
46+
47+
#new vertices which are "roots" get added to the queue
48+
if in_degree[vertex] == 0:
49+
queue.append(vertex)
50+
cnt += 1
51+
52+
if cnt != self.V:
53+
print "No topolocial ordering exists."
54+
55+
else:
56+
print top_order
57+
58+
59+
60+
61+
62+
#Normal case
63+
g= Graph(6)
64+
g.addEdge(5, 2);
65+
g.addEdge(5, 0);
66+
g.addEdge(4, 0);
67+
g.addEdge(4, 1);
68+
g.addEdge(2, 3);
69+
g.addEdge(3, 1);
70+
71+
print "Following is a Topological Sort of the given graph"
72+
g.topological_sort()
73+
74+
75+
76+
# Cyclic graph
77+
g2= Graph(6)
78+
g2.addEdge(5, 2);
79+
g2.addEdge(2, 5);
80+
g2.addEdge(4, 0);
81+
g2.addEdge(4, 1);
82+
g2.addEdge(2, 3);
83+
g2.addEdge(3, 1);
84+
g2.addEdge(5, 0);
85+
86+
print "Following is a Topological Sort of the given graph"
87+
g2.topological_sort()
88+

0 commit comments

Comments
 (0)