Back

Dijkstra's Shortest Path

Graph Selection

Playback Controls

Speed: 1000ms
Frame 1 of 0

Select start and target nodes to begin

Time: O((V + E) log V)
Space: O(V)

Reference implementation of Dijkstra's Algorithm. Select a language tab to view and copy the code.

import heapq

def dijkstra(adj: list[list[tuple[int,int]]], src: int) -> list[int]:
    n = len(adj)
    dist = [float('inf')] * n
    dist[src] = 0
    heap = [(0, src)]   # (distance, node)
    while heap:
        d, u = heapq.heappop(heap)
        if d > dist[u]:
            continue    # stale entry
        for v, w in adj[u]:
            if dist[u] + w < dist[v]:
                dist[v] = dist[u] + w
                heapq.heappush(heap, (dist[v], v))
    return dist

Python — Code Walkthrough

  1. heapq — min-heap by default

    import heapq; heap = [(0, src)]

    Python's heapq module provides a min-heap. Tuples are compared lexicographically, so (distance, node) naturally orders by distance first. No comparator class needed.

  2. float("inf") as initial distance

    dist = [float("inf")] * n

    float("inf") is always greater than any integer, acts as a safe infinity, and avoids the overflow risk of INT_MAX + any integer.

  3. Stale-entry skip

    if d > dist[u]: continue

    Lazy deletion: if a node was already settled with a shorter path since this entry was pushed, skip it. This keeps the algorithm correct without a decrease-key operation.

  4. heappush on improvement only

    heapq.heappush(heap, (dist[v], v))

    Only push a new entry when we find a shorter path. Each edge can cause at most one push, so the heap contains at most O(E) entries total.