Skip to content

Commit 15bcd92

Browse files
committed
fix(graphs): use deque and dict for kahns algorithm sparse vertices
1 parent 11d2a47 commit 15bcd92

1 file changed

Lines changed: 16 additions & 6 deletions

File tree

graphs/kahns_algorithm_topo.py

Lines changed: 16 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,17 @@ 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_cycle = {10: [20], 20: [10]}
33+
>>> topological_sort(sparse_cycle)
2434
"""
2535

26-
indegree = [0] * len(graph)
27-
queue = []
36+
indegree = dict.fromkeys(graph, 0)
37+
queue: deque[int] = deque()
2838
topo_order = []
2939
processed_vertices_count = 0
3040

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

3646
# 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)
47+
for vertex, count in indegree.items():
48+
if count == 0:
49+
queue.append(vertex)
4050

4151
# Perform BFS
4252
while queue:
43-
vertex = queue.pop(0)
53+
vertex = queue.popleft()
4454
processed_vertices_count += 1
4555
topo_order.append(vertex)
4656

0 commit comments

Comments
 (0)