Lesson 1 · Unit 04
Dijkstra's algorithm
Closest node first, with a heap
What you practise
- Relaxation, the priority queue, stale entries
Try a question from this lesson
Pick one
The direct road from home to the shop is 4 km. Home to the gym is 1 km, and the gym to the shop is 2 km. What is the shortest way from home to the shop?
Correct answer
3 km: go past the gym
Why
Two roads totalling 3 km beat one road of 4 km. Breadth-first search counts edges, so it would pick the direct road. Once edges have weights, the fewest edges and the shortest route are different questions.
The ideas
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
Relaxing an edge
Keep the best distance found so far for every node: 0 for the start, infinity for the others.
To relax an edge from u to v with weight w, ask: is going through u shorter than what v has now? If so, lower it. Every shortest-path algorithm is built from this one step.
INF = float("inf")
# nodes: home, gym, shop
dist = [0, INF, INF]
def relax(u, v, w):
if dist[u] + w < dist[v]:
dist[v] = dist[u] + w
relax(0, 2, 4) # shop: 4
relax(0, 1, 1) # gym: 1
relax(1, 2, 2) # shop: 3
print(dist[2])const INF = Infinity;
// nodes: home, gym, shop
const dist = [0, INF, INF];
function relax(u, v, w) {
if (dist[u] + w < dist[v]) {
dist[v] = dist[u] + w;
}
}
relax(0, 2, 4); // shop: 4
relax(0, 1, 1); // gym: 1
relax(1, 2, 2); // shop: 3
console.log(dist[2]);const INF = Infinity;
// nodes: home, gym, shop
const dist = [0, INF, INF];
function relax(
u: number, v: number, w: number,
) {
if (dist[u] + w < dist[v]) {
dist[v] = dist[u] + w;
}
}
relax(0, 2, 4); // shop: 4
relax(0, 1, 1); // gym: 1
relax(1, 2, 2); // shop: 3
console.log(dist[2]);Python notefloat("inf") is larger than every number, and adding to it still gives infinity.
JavaScript noteInfinity is larger than every number, and Infinity + 2 is still Infinity.
TypeScript noteInfinity has type number, so dist is inferred as a plain number[].
Concept
Dijkstra with a heap
A min-heap of (distance, node) pairs hands over the closest node each time. Popping a node relaxes its edges, and every improvement is pushed as a new pair.
Old pairs for the same node stay in the heap. When one surfaces later it is worse than the recorded distance, so it is skipped.
from heapq import heappush, heappop
def dijkstra(adj):
dist = [float("inf")] * len(adj)
dist[0] = 0
heap = [(0, 0)]
while heap:
d, u = heappop(heap)
if d > dist[u]:
continue # outdated pair
for v, w in adj[u]:
if d + w < dist[v]:
dist[v] = d + w
heappush(heap, (d + w, v))
return distfunction dijkstra(adj) {
const dist = adj.map(() => Infinity);
dist[0] = 0;
const heap = new MinHeap();
heap.push([0, 0]);
while (heap.size > 0) {
const [d, u] = heap.pop();
if (d > dist[u]) continue; // outdated
for (const [v, w] of adj[u]) {
if (d + w >= dist[v]) continue;
dist[v] = d + w;
heap.push([d + w, v]);
}
}
return dist;
}function dijkstra(adj: Hop[][]) {
const dist = adj.map(() => Infinity);
dist[0] = 0;
const heap = new MinHeap();
heap.push([0, 0]);
while (heap.size > 0) {
const [d, u] = heap.pop();
if (d > dist[u]) continue; // outdated
for (const [v, w] of adj[u]) {
if (d + w >= dist[v]) continue;
dist[v] = d + w;
heap.push([d + w, v]);
}
}
return dist;
}Python noteheapq turns a plain list into a min-heap. Tuples compare by their first item first, so the smallest distance is popped first.
JavaScript noteJavaScript has no built-in heap. MinHeap is the class from the Trees & Heaps roadmap: push adds a pair and pop removes the pair with the smallest first item.
TypeScript noteMinHeap is the class from the Trees & Heaps roadmap: pop removes the pair with the smallest first item. Hop is an alias for [number, number].
8 more exercises in the app
- 2× type the answer
- 3× multiple choice
- 1× fill the blanks
- 1× true or false
- 1× match the pairs
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.