mirror of
https://github.com/TheAlgorithms/Python.git
synced 2024-11-30 16:31:08 +00:00
1f8a21d727
* Tighten up psf/black and flake8 * Fix some tests * Fix some E741 * Fix some E741 * updating DIRECTORY.md Co-authored-by: github-actions <${GITHUB_ACTOR}@users.noreply.github.com>
37 lines
819 B
Python
37 lines
819 B
Python
def topologicalSort(graph):
|
|
"""
|
|
Kahn's Algorithm is used to find Topological ordering of Directed Acyclic Graph
|
|
using BFS
|
|
"""
|
|
indegree = [0] * len(graph)
|
|
queue = []
|
|
topo = []
|
|
cnt = 0
|
|
|
|
for key, values in graph.items():
|
|
for i in values:
|
|
indegree[i] += 1
|
|
|
|
for i in range(len(indegree)):
|
|
if indegree[i] == 0:
|
|
queue.append(i)
|
|
|
|
while queue:
|
|
vertex = queue.pop(0)
|
|
cnt += 1
|
|
topo.append(vertex)
|
|
for x in graph[vertex]:
|
|
indegree[x] -= 1
|
|
if indegree[x] == 0:
|
|
queue.append(x)
|
|
|
|
if cnt != len(graph):
|
|
print("Cycle exists")
|
|
else:
|
|
print(topo)
|
|
|
|
|
|
# Adjacency List of Graph
|
|
graph = {0: [1, 2], 1: [3], 2: [3], 3: [4, 5], 4: [], 5: []}
|
|
topologicalSort(graph)
|