Shortest Paths (Dijkstra)

Data Structures & Algorithms · Graph Algorithms · Advanced · 18 min

How Google Maps finds the fastest route when roads have different lengths.

Water poured at the start city, flowing along roads of different lengths. A city becomes "wet" (final) only when the water front reaches it, and the front always arrives at the closest dry city next. A min-heap is the clerk who always knows which city the water reaches next.

The idea in everyday words

Pour water at the start city. It flows along roads; it reaches close cities first and far cities later. The moment water first touches a city, you've found the shortest time to it. Dijkstra simulates that flood using a priority queue.

Why BFS isn't enough

BFS counts edges. With weights (road lengths), 1 long road may be worse than 3 short ones. Dijkstra always expands the closest unvisited city next: a min-heap gives it to us quickly.

The algorithm

import heapq
def dijkstra(graph, start):
    dist = {start: 0}
    heap = [(0, start)]
    while heap:
        d, node = heapq.heappop(heap)
        if d > dist.get(node, float("inf")):
            continue                      # stale entry
        for nb, w in graph.get(node, []):
            nd = d + w
            if nd < dist.get(nb, float("inf")):
                dist[nb] = nd
                heapq.heappush(heap, (nd, nb))
                print("improved", nb, "to", nd)
    return dist

g = {"A": [("B", 4), ("C", 1)], "C": [("B", 2), ("D", 5)], "B": [("D", 1)]}
print(dijkstra(g, "A"))

Notice B first gets 4 (direct) and is then improved to 3 via C.

Step by step

  1. Start:

    The challenge graph: 0→1 costs 4, 0→2 costs 1, 2→1 costs 2, 1→3 costs 1. Source 0. dist = [0, ∞, ∞, ∞], heap [(0, node 0)].

  2. Pop node 0 (dist 0):

    Relax its roads: dist[1] = 4, dist[2] = 1. Both offers go on the heap.

  3. Pop node 2 (dist 1):

    It is the closest, so 1 is final. Road 2→1: 1 + 2 = 3 < 4, so dist[1] improves to 3. Push (3, node 1).

  4. Pop node 1 (dist 3):

    Final at 3, cheaper than the direct road. Road 1→3: dist[3] = 3 + 1 = 4.

  5. Stale offer:

    The old offer (4, node 1) comes out next, but 4 > dist[1] = 3, so skip it.

  6. Done:

    Pop node 3 (dist 4): no roads out. Answer [0, 3, 1, 4].

Code example

import heapq
def network_delay(times, n, k):
    graph = {}
    for u, v, w in times:
        graph.setdefault(u, []).append((v, w))
    dist, heap = {}, [(0, k)]
    while heap:
        d, u = heapq.heappop(heap)
        if u in dist: continue
        dist[u] = d
        for v, w in graph.get(u, []):
            if v not in dist:
                heapq.heappush(heap, (d + w, v))
    return max(dist.values()) if len(dist) == n else -1

print(network_delay([[2, 1, 1], [2, 3, 1], [3, 4, 1]], 4, 2))

Complexity

  • Time: O((V + E) log V) with a heap
  • Space: O(V + E)

Interview tips

  • Network Delay Time, Cheapest Flights, Path With Minimum Effort.

  • Explain why it fails with negative edges.

Challenge: Shortest Distances

Nodes are 0..n-1. edges are directed [from, to, weight]. Return a list of the shortest distance from src to every node, using -1 for unreachable nodes.

Example: shortest(4, [[0,1,4],[0,2,1],[2,1,2],[1,3,1]], 0) → [0, 3, 1, 4]

Solve it in the browser with tests, hints and an AI coach.

Practice problems

More in Graph Algorithms

Previous: Topological Sort & DAGs · Next: Minimum Spanning Trees