Python/graphs/kahns_algorithm_topo.py

34 lines
769 B
Python
Raw Normal View History

2018-10-19 12:48:28 +00:00
# Kahn's Algorithm is used to find Topological ordering of Directed Acyclic Graph using BFS
def topologicalSort(l):
indegree = [0] * len(l)
queue = []
topo = []
cnt = 0
for key, values in l.items():
for i in values:
indegree[i] += 1
for i in range(len(indegree)):
if indegree[i] == 0:
queue.append(i)
2019-10-05 05:14:13 +00:00
while queue:
2018-10-19 12:48:28 +00:00
vertex = queue.pop(0)
cnt += 1
topo.append(vertex)
for x in l[vertex]:
indegree[x] -= 1
if indegree[x] == 0:
queue.append(x)
if cnt != len(l):
print("Cycle exists")
else:
print(topo)
2019-10-05 05:14:13 +00:00
2018-10-19 12:48:28 +00:00
# Adjacency List of Graph
2019-10-05 05:14:13 +00:00
l = {0: [1, 2], 1: [3], 2: [3], 3: [4, 5], 4: [], 5: []}
2018-10-19 12:48:28 +00:00
topologicalSort(l)