Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 17 additions & 6 deletions graphs/kahns_algorithm_topo.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
from collections import deque


def topological_sort(graph: dict[int, list[int]]) -> list[int] | None:
"""
Perform topological sorting of a Directed Acyclic Graph (DAG)
Expand All @@ -21,10 +24,18 @@ def topological_sort(graph: dict[int, list[int]]) -> list[int] | None:

>>> graph_with_cycle = {0: [1], 1: [2], 2: [0]}
>>> topological_sort(graph_with_cycle)

>>> sparse_graph = {10: [20], 20: []}
>>> topological_sort(sparse_graph)
[10, 20]

>>> sparse_graph = {10: [20, 30], 20: [40], 30: [40], 40: []}
>>> topological_sort(sparse_graph)
[10, 20, 30, 40]
"""

indegree = [0] * len(graph)
queue = []
indegree = dict.fromkeys(graph, 0)
queue = deque()
topo_order = []
processed_vertices_count = 0

Expand All @@ -34,13 +45,13 @@ def topological_sort(graph: dict[int, list[int]]) -> list[int] | None:
indegree[i] += 1

# Add all vertices with 0 indegree to the queue
for i in range(len(indegree)):
if indegree[i] == 0:
queue.append(i)
for vertex in graph:
if indegree[vertex] == 0:
queue.append(vertex)

# Perform BFS
while queue:
vertex = queue.pop(0)
vertex = queue.popleft()
processed_vertices_count += 1
topo_order.append(vertex)

Expand Down