MCPcopy Index your code
hub / github.com/subbarayudu-j/TheAlgorithms-Python / topologicalSort

Function topologicalSort

Graphs/kahns_algorithm_topo.py:2–28  ·  view source on GitHub ↗
(l)

Source from the content-addressed store, hash-verified

1# Kahn's Algorithm is used to find Topological ordering of Directed Acyclic Graph using BFS
2def topologicalSort(l):
3 indegree = [0] * len(l)
4 queue = []
5 topo = []
6 cnt = 0
7
8 for key, values in l.items():
9 for i in values:
10 indegree[i] += 1
11
12 for i in range(len(indegree)):
13 if indegree[i] == 0:
14 queue.append(i)
15
16 while(queue):
17 vertex = queue.pop(0)
18 cnt += 1
19 topo.append(vertex)
20 for x in l[vertex]:
21 indegree[x] -= 1
22 if indegree[x] == 0:
23 queue.append(x)
24
25 if cnt != len(l):
26 print("Cycle exists")
27 else:
28 print(topo)
29
30# Adjacency List of Graph
31l = {0:[1,2], 1:[3], 2:[3], 3:[4,5], 4:[], 5:[]}

Callers 1

Calls 1

popMethod · 0.45

Tested by

no test coverage detected