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 distWhat the code does
Dijkstra Shortest Path With Min Heap (Python) is built around the function dijkstra.
Iteration happens inside while heap — everything outside it runs once.
Points of care
heapqmust be installed first — the snippet imports it directly.
Applying it
Entry signature: def dijkstra(graph, start)
dijkstra is what another module would consume; nothing else here is load-bearing for callers.
Interactive Tools for This Topic
FAQ
- Which packages does this snippet need?
- None. Every symbol the code uses resolves inside the standard library. The file defines `dijkstra` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.