Dijkstra Shortest Path With Min Heap (Python)
Compute single source shortest paths in a weighted graph using Dijkstra with heapq for efficient extraction.
Code
import heapq
def dijkstra(graph, start):
dist = {n: float("inf") for n in graph}
dist[start] = 0
heap = [(0, start)]
while heap:
d, node = heapq.heappop(heap)
if d > dist[node]:
continue
for neighbor, weight in graph.get(node, []):
nd = d + weight
if nd < dist[neighbor]:
dist[neighbor] = nd
heapq.heappush(heap, (nd, neighbor))
return distReport a problem with this exampleOpens a pre-filled issue on GitHub.