2020-05-22 06:10:11 +00:00
|
|
|
def topologicalSort(graph):
|
|
|
|
"""
|
|
|
|
Kahn's Algorithm is used to find Topological ordering of Directed Acyclic Graph
|
|
|
|
using BFS
|
|
|
|
"""
|
|
|
|
indegree = [0] * len(graph)
|
2018-10-19 12:48:28 +00:00
|
|
|
queue = []
|
|
|
|
topo = []
|
|
|
|
cnt = 0
|
|
|
|
|
2020-05-22 06:10:11 +00:00
|
|
|
for key, values in graph.items():
|
2018-10-19 12:48:28 +00:00
|
|
|
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)
|
2020-05-22 06:10:11 +00:00
|
|
|
for x in graph[vertex]:
|
2018-10-19 12:48:28 +00:00
|
|
|
indegree[x] -= 1
|
|
|
|
if indegree[x] == 0:
|
|
|
|
queue.append(x)
|
|
|
|
|
2020-05-22 06:10:11 +00:00
|
|
|
if cnt != len(graph):
|
2018-10-19 12:48:28 +00:00
|
|
|
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
|
2020-05-22 06:10:11 +00:00
|
|
|
graph = {0: [1, 2], 1: [3], 2: [3], 3: [4, 5], 4: [], 5: []}
|
|
|
|
topologicalSort(graph)
|