Dijkstra Shortest Path With Min Heap (Python)

Compute single source shortest paths in a weighted graph using Dijkstra with heapq for efficient extraction.

PythonData Fetching

Code

snippet
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 dist