Skip to content
Closed
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
17 changes: 10 additions & 7 deletions graphs/kahns_algorithm_topo.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,24 +23,27 @@
>>> topological_sort(graph_with_cycle)
"""

indegree = [0] * len(graph)
queue = []
from collections import deque

# Use dict for indegree to support sparse/non-contiguous vertex IDs
indegree: dict[int, int] = {v: 0 for v in graph}

Check failure on line 29 in graphs/kahns_algorithm_topo.py

View workflow job for this annotation

GitHub Actions / ruff

ruff (C420)

graphs/kahns_algorithm_topo.py:29:32: C420 Unnecessary dict comprehension for iterable; use `dict.fromkeys` instead help: Replace with `dict.fromkeys(iterable)`)
queue: deque[int] = deque()
topo_order = []
processed_vertices_count = 0

# Calculate the indegree of each vertex
for values in graph.values():
for i in values:
indegree[i] += 1
indegree[i] = indegree.get(i, 0) + 1

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

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

Expand Down
Loading