Dijkstra's algorithm
medium 22 minDijkstra's algorithm finds the shortest distance from one source to every node of a graph whose edge weights are non-negative.
Video lesson · Chapter 1 of 7
The express road loses
Dijkstra's algorithm in 75 seconds
1:27Reel
How it works
Step through the idea, or press Play.
Start at the source. dist(source) = 0, every other node is infinity, and the heap holds (0, source)
Understand it
Start here
Shortest paths when edges have weights
In an unweighted graph, BFS finds shortest paths because every edge costs the same. Give the edges weights (minutes, kilometres, milliseconds) and the fewest hops is no longer the cheapest route. Dijkstra's algorithm (Edsger Dijkstra, 1956) answers: what is the cheapest route from one source to every node, when no weight is negative?
What you already know
Graphs
Nodes, weighted edges, adjacency lists
{u: [(v, w), ...]}. Recap in intro to graphs.Min-heaps
heapqpops the smallest tuple in . Recap in priority queues and heap operations.BFS
A FIFO queue explores in order of hop count. Dijkstra swaps the queue for a min-heap and explores in order of distance.
The core move
Relaxation
Every node carries a tentative distance : the best route found so far, an upper bound on the true distance . To relax the edge with weight is to ask: is going through better than what has now? If so, take it and remember as 's predecessor.
Relaxing edge (u, v) with weight w
One relaxation
| Relaxation in the simple graph | Check | Result |
|---|---|---|
| A to B (w 4) | dist(B) = 4 | |
| C to B (w 1) | dist(B) = 3, prev(B) = C | |
| C to D (w 8) then B to D (w 5) | , then | dist(D) = 8 |
| D to E (w 2) | dist(E) = 10 |
The algorithm
A min-heap loop with lazy deletion
The Dijkstra loop
import heapqdef dijkstra(graph, src): dist = {v: float("inf") for v in graph} prev = {v: None for v in graph} dist[src] = 0 pq = [(0, src)] # (distance, node): distance first! while pq: d, u = heapq.heappop(pq) # closest entry if d > dist[u]: continue # stale: u was settled cheaper for v, w in graph[u]: nd = d + w if nd < dist[v]: # relax dist[v] = nd prev[v] = u heapq.heappush(pq, (nd, v)) return dist, prevgraph = { "A": [("B", 4), ("C", 2)], "B": [("A", 4), ("C", 1), ("D", 5)], "C": [("A", 2), ("B", 1), ("D", 8), ("E", 10)], "D": [("B", 5), ("C", 8), ("E", 2), ("F", 6)], "E": [("C", 10), ("D", 2), ("F", 3)], "F": [("D", 6), ("E", 3)],}dist, prev = dijkstra(graph, "A")print(dist) # {'A': 0, 'B': 3, 'C': 2, 'D': 8, 'E': 10, 'F': 13}Six implementation details
Min-heap
Extract the closest entry in . Tuples are
(distance, node)so the heap orders by distance.Lazy deletion
Never search the heap. Push a fresh entry on every improvement and skip stale ones on pop.
Distance map
dist[v]: the best known distance, starting at .Predecessor map
prev[v]: who gave its distance. Rebuilds every route afterwards.Non-negative weights
Required for the greedy choice to be correct. One negative edge breaks it.
Adjacency list
Iterate a node's neighbours in , so all relaxations total .
Worked example
Tracing the simple graph from A
Six nodes A to F, nine two-way edges: A–B 4, A–C 2, B–C 1, B–D 5, C–D 8, C–E 10, D–E 2, D–F 6, E–F 3. Source A. Step through it in the visualizer too.
- 1
Initialise
dist: A , everything else . Heap:
(0, A). - 2
Settle A
Relax A–B and A–C: B , C . Heap:
(2, C), (4, B). - 3
The greedy choice: C, not B
C at 2 is the minimum, so it is settled. Through C, B improves ; D , E . The old
(4, B)is now stale. - 4
Settle B at 3
B–D: . Then
(4, B)pops and is skipped. - 5
Settle D at 8
D–E: , D–F: . Then
(10, D)is stale and skipped. - 6
Settle E at 10, F at 13
E–F: . Stale
(12, E)and(14, F)are skipped. Final: A 0, B 3, C 2, D 8, E 10, F 13.
dist after each settle
| Settled | A | B | C | D | E | F |
|---|---|---|---|---|---|---|
| (start) | 0 | ∞ | ∞ | ∞ | ∞ | ∞ |
| A | 0 | 4 | 2 | ∞ | ∞ | ∞ |
| C | 0 | 3 | 2 | 10 | 12 | ∞ |
| B | 0 | 3 | 2 | 8 | 12 | ∞ |
| D | 0 | 3 | 2 | 8 | 10 | 14 |
| E | 0 | 3 | 2 | 8 | 10 | 13 |
| F | 0 | 3 | 2 | 8 | 10 | 13 |
Lazy deletion
Stale entries and why they are harmless
When B improved from 4 to 3, the textbook move is decrease-key: find (4, B) inside the heap and lower it. Python's heapq cannot find an entry without an scan, so we push (3, B) and leave (4, B) behind. When it finally pops, tells us it is out of date: skip it. This is the same lazy deletion trick from priority queues.
The life of one node
Lazy deletion (heapq)
- Push on every improvement, skip
d > dist[u]on pop - No index map, about 10 lines of code
- Heap can grow to entries
- Same bound
Decrease-key (indexed heap)
- Needs a node-to-slot map updated on every swap
- Heap never exceeds entries
- More code, more bugs in an interview
- Java and C++ standard queues lack it too
Correctness
Why the popped node is final
Claim. When a node is popped with (not stale), . Proof by contradiction. Let be the first node settled with . Take a true shortest path from to , and let be the first node on it that is not yet settled, with just before it (settled, so correct by the choice of ). When was settled, edge was relaxed, so .
The chain that cannot hold
The proof picture
Complexity
O((V + E) log V) and when an array wins
Counting heap operations
Three ways to find the minimum
| Priority structure | Extract-min | Improve a distance | Total | Best for |
|---|---|---|---|---|
| Plain array, scan for min | Dense graphs, | |||
| Binary heap (heapq) | push | Sparse graphs: roads, networks, grids | ||
| Fibonacci heap | amortised | amortised decrease-key | Theory; constants too large in practice |
Where the array version wins
Limits
Why negative edges break it
The proof used in one place: "continuing past can only add cost". With a negative edge, a route that looks expensive now can become cheaper later, after a node was already declared final. Example (directed): A→B 2, A→C 3, C→B , B→D 1. The true distances are B , D .
A negative edge arrives too late
| Algorithm | Negative edges | Negative cycles | Time |
|---|---|---|---|
| Dijkstra | No | No | |
| Bellman-Ford | Yes | Detects them | : relax all edges times |
| Floyd-Warshall (all pairs) | Yes | Detects them | |
| Johnson (all pairs, sparse) | Yes, by reweighting | Detects them |
Paths
Rebuilding the route with prev
Distances say how far, not which way. Every successful relaxation sets , and the last one written is the final predecessor. Walk from the target back to the source, then reverse.
Walking prev from F
def path_to(prev, dist, target): if dist[target] == float("inf"): return [] # never reached path, node = [], target while node is not None: path.append(node) node = prev[node] return path[::-1]dist = {"A": 0, "B": 3, "C": 2, "D": 8, "E": 10, "F": 13, "Z": float("inf")}prev = {"A": None, "B": "C", "C": "A", "D": "B", "E": "D", "F": "E", "Z": None}print(path_to(prev, dist, "F")) # ['A', 'C', 'B', 'D', 'E', 'F']print(path_to(prev, dist, "Z")) # []Variants
Early exit, grids and networks
Single target: stop early
Return when the target is popped (not pushed). Saves work when the target is near; in the London to Rome scene all 10 cities settle anyway.
Weighted grids
Each cell is a node with up to 4 neighbours. Cost can be the cell value, or a max along the path as in minimum effort.
Networks
Signal delay from one router to all: run once, answer is the largest finite dist, or if any node is unreachable.
Other path costs
Maximum probability (multiply, use a max-heap) and minimum effort (max of steps) work because the cost never improves by extending a path.
import heapqdef cheapest_walk(grid): rows, cols = len(grid), len(grid[0]) dist = [[float("inf")] * cols for _ in range(rows)] dist[0][0] = grid[0][0] pq = [(grid[0][0], 0, 0)] while pq: d, r, c = heapq.heappop(pq) if d > dist[r][c]: continue if (r, c) == (rows - 1, cols - 1): return d # popped: final for dr, dc in ((1, 0), (-1, 0), (0, 1), (0, -1)): nr, nc = r + dr, c + dc if 0 <= nr < rows and 0 <= nc < cols and d + grid[nr][nc] < dist[nr][nc]: dist[nr][nc] = d + grid[nr][nc] heapq.heappush(pq, (dist[nr][nc], nr, nc)) return -1grid = [[1, 3, 1, 8], [1, 5, 1, 9], [4, 2, 1, 1]]print(cheapest_walk(grid)) # 1 + 3 + 1 + 1 + 1 + 1 = 8Classic problems that are Dijkstra underneath
| Problem (LeetCode) | Node | Edge cost | Twist |
|---|---|---|---|
| 743 Network Delay Time | router | delay | answer is max(dist), if unreachable |
| 1631 Path With Minimum Effort | cell | height difference | path cost is the max step, not the sum |
| 1514 Path with Maximum Probability | node | success probability | multiply and use a max-heap |
| 778 Swim in Rising Water | cell | cell height | path cost is the max cell |
| 787 Cheapest Flights Within K Stops | (city, stops) | price | state needs the stop count, or use Bellman-Ford with K + 1 rounds |
| 882 Reachable Nodes in Subdivided Graph | node | subdivisions + 1 | count leftover moves on each edge |
Choosing
Dijkstra, BFS, Bellman-Ford or something else
Which shortest-path algorithm?
| Dijkstra | BFS | Bellman-Ford | |
|---|---|---|---|
| Edge weights | Non-negative | Unweighted (all equal) | Any, including negative |
| Time | |||
| Data structure | Priority queue (min-heap) | Queue | Edge list, passes |
| Best for | Road networks, routing | Social networks, mazes | Negative weights, cycle detection |
Use Dijkstra when
- You need shortest paths from one source
- All edge weights are non-negative
- The graph is sparse ( well below )
- You want paths to every node, or one target with early exit
Do not use it when
- Any weight is negative: use Bellman-Ford
- The graph is unweighted: BFS is simpler and faster
- You need all-pairs distances: use Floyd-Warshall
- A path constraint (at most K stops) changes the state
Recap
Key takeaways
Key points
- Dijkstra finds single-source shortest paths when every edge weight is ; it is BFS with a min-heap keyed by distance.
- Relax edge : if , lower , set and push.
- A node is final when popped, not when first pushed; stale entries () are skipped. That is lazy deletion.
- Correctness: any route that leaves the settled set is already at least as long, and non-negative edges only add.
- Time with a binary heap, with an array (better when dense), with a Fibonacci heap.
- Negative edges break it: use Bellman-Ford. Rebuild routes by walking
prevback from the target and reversing.