Skip to content

Commit f9f8f76

Browse files
Fix Kahn's algorithm
1 parent f5988cc commit f9f8f76

1 file changed

Lines changed: 17 additions & 6 deletions

File tree

graphs/kahns_algorithm_topo.py

Lines changed: 17 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,6 @@
1+
from collections import deque
2+
3+
14
def topological_sort(graph: dict[int, list[int]]) -> list[int] | None:
25
"""
36
Perform topological sorting of a Directed Acyclic Graph (DAG)
@@ -21,10 +24,18 @@ def topological_sort(graph: dict[int, list[int]]) -> list[int] | None:
2124
2225
>>> graph_with_cycle = {0: [1], 1: [2], 2: [0]}
2326
>>> topological_sort(graph_with_cycle)
27+
28+
>>> sparse_graph = {10: [20], 20: []}
29+
>>> topological_sort(sparse_graph)
30+
[10, 20]
31+
32+
>>> sparse_graph = {10: [20, 30], 20: [40], 30: [40], 40: []}
33+
>>> topological_sort(sparse_graph)
34+
[10, 20, 30, 40]
2435
"""
2536

26-
indegree = [0] * len(graph)
27-
queue = []
37+
indegree = dict.fromkeys(graph, 0)
38+
queue = deque()
2839
topo_order = []
2940
processed_vertices_count = 0
3041

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

3647
# Add all vertices with 0 indegree to the queue
37-
for i in range(len(indegree)):
38-
if indegree[i] == 0:
39-
queue.append(i)
48+
for vertex in graph:
49+
if indegree[vertex] == 0:
50+
queue.append(vertex)
4051

4152
# Perform BFS
4253
while queue:
43-
vertex = queue.pop(0)
54+
vertex = queue.popleft()
4455
processed_vertices_count += 1
4556
topo_order.append(vertex)
4657

0 commit comments

Comments
 (0)