Dijkstra in code
After this: Follow Dijkstra's algorithm with a heap on the full graph, skip stale entries and read the code.
On this page · 9 sections · 2 checks
In the last lesson, you ran Dijkstra's algorithm by hand on three nodes. A program needs the same steps in a form that works on any graph. This lesson adds the last pieces: a heap for the waiting list, a name for out-of-date notes, and the code. The idea does not change.
The waiting list is a heap
The waiting list must give us the smallest distance every time. A does exactly this. You met it in the heaps tutorial. To push means to put an entry in. To pop means to take out the smallest entry. Java's PriorityQueue calls these add and poll.
In the tables, we write an entry as (B, 4): the node, then its distance. The code stores the distance first, because a heap compares the first value first. Both forms hold the same two facts.
Stale entries
In the last lesson's table, (B, 4) stayed on the list after we found a better distance for B. The same happens in a heap. heapqPriorityQueue cannot change an entry that is already inside, so we push a new entry and leave the old one where it is.
An out-of-date entry is called a . It does no harm. When it comes out, we compare its distance with the table, see that it is worse, and skip it.
The full method
Here is the method again, using these words.
- Set the start's distance to 0 and every other distance to ∞. Push the start.
- Pop the smallest entry.
- If its distance is worse than the table's, the entry is stale. Skip it.
- Otherwise the node is final. Relax each edge that leaves it.
- Go back to step 2. Stop when the heap is empty.
Five nodes
Here is the full graph from the first lesson. The steps are the same. There are more rows, and two stale entries.
We list the table in the order A B C D E.
| Pop | Edges relaxed | Table after | Heap after |
|---|---|---|---|
| (A, 0) | A→B: 4 beats ∞. A→C: 1 beats ∞ | 0 4 1 ∞ ∞ | (C, 1) (B, 4) |
| (C, 1) | C→B: 1 + 2 = 3 beats 4. C→D: 1 + 5 = 6 beats ∞ | 0 3 1 6 ∞ | (B, 3) (B, 4) (D, 6) |
| (B, 3) | B→D: 3 + 1 = 4 beats 6 | 0 3 1 4 ∞ | (B, 4) (D, 4) (D, 6) |
| (B, 4) | stale: B is final at 3, so skip it | 0 3 1 4 ∞ | (D, 4) (D, 6) |
| (D, 4) | D→E: 4 + 3 = 7 beats ∞ | 0 3 1 4 7 | (D, 6) (E, 7) |
| (D, 6) | stale: D is final at 4, so skip it | 0 3 1 4 7 | (E, 7) |
| (E, 7) | no edges leave E | 0 3 1 4 7 | empty |
There were seven pops. Five finalised a node, in the order A, C, B, D, E. Two found a stale entry and skipped it. The final distances are A 0, B 3, C 1, D 4 and E 7.
Watch it happen
Before the first run, the task asks for a prediction: tap the node you think is finalised right after A. Then watch the heap decide.
- Dijkstra from AStep through from A. Five pops finalise a node. Two pops find a stale entry and skip it. Watch for those two.
- Dijkstra from E
Pick a start node and run an algorithm.
The code
import heapq
def dijkstra(graph, start): distances = {node: float("inf") for node in graph} distances[start] = 0 parents = {start: None} heap = [(0, start)] # (distance, node): the smallest distance pops first while heap: dist, node = heapq.heappop(heap) if dist > distances[node]: # stale: out of date, node is already final continue for next_node, weight in graph[node]: new_dist = dist + weight if new_dist < distances[next_node]: # relax: a shorter way to next_node distances[next_node] = new_dist parents[next_node] = node heapq.heappush(heap, (new_dist, next_node)) return distances, parentsimport java.util.*;
public class Dijkstra { record Entry(int dist, String node) {} // (distance, node): the smallest distance polls first record Result(Map<String, Integer> distances, Map<String, String> parents) {}
static Result run(Map<String, List<Edge>> graph, String start) { Map<String, Integer> distances = new HashMap<>(); for (String node : graph.keySet()) distances.put(node, Integer.MAX_VALUE); // stands in for infinity distances.put(start, 0); Map<String, String> parents = new HashMap<>(); parents.put(start, null); PriorityQueue<Entry> heap = new PriorityQueue<>(Comparator.comparingInt(Entry::dist).thenComparing(Entry::node)); heap.add(new Entry(0, start)); while (!heap.isEmpty()) { Entry e = heap.poll(); if (e.dist() > distances.get(e.node())) continue; // stale: out of date, node is already final for (Edge edge : graph.get(e.node())) { int newDist = e.dist() + edge.weight(); if (newDist < distances.get(edge.to())) { // relax: a shorter way to edge.to distances.put(edge.to(), newDist); parents.put(edge.to(), e.node()); heap.add(new Entry(newDist, edge.to())); } } } return new Result(distances, parents); }}Here is how to read it.
distancesis the table. Every node starts at infinity, except the start. float("inf")Integer.MAX_VALUE stands for ∞.parentsis for the next lesson. You can ignore it for now.heapis the waiting list, and it starts with the start node at distance 0.- The
whileloop pops the smallest entry each time. - The first
ifinside the loop is the stale check. - The
forloop goes through the edges that leave the node. - The highlighted lines relax one edge.
The code has no line that says "finalise". A node becomes final when its smallest entry is popped. Any entry for that node that comes out later is stale, so the node is not worked on twice.
distances, parents = dijkstra(graph, "A")for node in graph: print(node, distances[node])A 0 B 3 C 1 D 4 E 7
Dijkstra.Result result = Dijkstra.run(graph, "A");for (String node : graph.keySet()) System.out.println(node + " " + result.distances().get(node));A 0 B 3 C 1 D 4 E 7
How fast is it?
Programmers describe speed by how the number of steps grows with the data. O(n) means that the steps grow at the same rate as the data. Counting steps explains this. O(log n) means that the steps grow very slowly: if the data doubles, the work goes up by about one step. Push and pop on a heap both cost O(log n), which is about 20 steps for a million entries.
For a graph, we use V for the number of nodes and E for the number of edges.
- Setting up the table takes V steps.
- Each node is finalised once, so each edge is relaxed at most once.
- So at most E entries are pushed, plus one for the start, and each one is popped once.
- Each push and pop costs O(log E). A graph has at most V × V edges, so log E is at most 2 × log V, and we write this as O(log V).
Together this gives O((V + E) log V). In words, the work is about the size of the graph, times a small number. This is fast enough for road maps.
Check yourself
After C is popped, the heap holds (B, 3), (B, 4) and (D, 6). Each entry is a node and its distance. Which entry comes out next, and what happens to it?
Later the heap gives (B, 4), but B was already finalised at 3. What does the algorithm do?
Connect
- Use a min-heap as the waiting list: push every improvement, and pop the smallest entry.
- Recognise a stale entry, one that is out of date, and skip it.
- Give the final table for the five-node graph: A 0, B 3, C 1, D 4, E 7.
- Say what a run costs: O((V + E) log V).