Find the cheapest route when steps cost different amounts, with a heap of tentative distances.
A maps app helps delivery couriers get from a restaurant to a customer. Your team lead explains the problem.
Your team lead says: The app shows the route with the fewest roads. Couriers say it is often slower. I need the route that takes the fewest minutes.
The city is a map of junctions joined by one-way roads, and each road takes its own number of minutes. Here is a small map. Each line says from to minutes.
0 1 4 3 4 3
0 2 1 1 5 7
2 1 2 4 5 1
1 3 1
2 3 5The courier starts at junction 0, and the customer is at junction 5. Two questions come up all the time:
You already know a search that finds the fewest roads: BFS, from BFS and DFS on a grid (A1). It spreads in rings, and ring number three means three roads.
On this map, BFS reaches junction 5 by 0, 1, 5: two roads. But those two roads cost 4 + 7 = 11 minutes. The cheapest route is 0, 2, 1, 3, 4, 5: five roads, but only 1 + 2 + 1 + 3 + 1 = 8 minutes.
So rings of roads are the wrong measure now. This lesson fixes that with two algorithms. Dijkstra's algorithm finds the cheapest route when no road has a negative cost. Bellman-Ford is slower but also copes with negative costs.
This lesson uses a heap, which you met in Heaps and priority queues (S5), and a graph stored as lists of roads, from Graphs (S6).
You plan a metro trip. You know the ride time between neighbouring stations, and you want the fastest way to every station. You keep a list of stations you have not settled yet, each with the best time you know so far.
Each time, you settle the station you can reach soonest. Its time cannot get better, because every other way in goes through a station that is at least as far away. Then you check the rides that leave it: does going this way make a neighbour sooner?
Dijkstra's algorithm works the same way, with a min-heap as the waiting list.
Dijkstra works like a metro trip planner: always settle the station you can reach soonest, then check its rides.
You compare flight prices between cities. You keep a board with the cheapest price you know to each city, and at first only your home city is on it. Then you do rounds. In each round you check every flight.
If the price to its start city plus the flight is below the price on the board for its end city, you lower that price.
You stop when a whole round changes nothing. A flight with a negative price, such as a refund voucher, is no problem for this board.
Bellman-Ford works the same way: rounds over every road, with no settled stations.
Predict what happens
Q On the map above, BFS reaches junction 3 through 0, 1, 3. That is two roads and 5 minutes. Is that the cheapest way to junction 3?
Answer: B
BFS counts roads, not minutes. The route 0, 2, 1, 3 has more roads but each one is quick, and it takes 4 minutes. The route 0, 2, 3 takes 1 + 5 = 6 minutes, and 0, 1, 3 takes 4 + 1 = 5.
Dijkstra keeps two things for each junction: its distance, the cheapest cost found so far (at first none, shown as ∞), and whether it is final. It also keeps a min-heap of waiting entries, each one a pair (distance, junction). The smallest distance leaves the heap first.
Each step has two parts:
The player below runs Dijkstra from junction 0. The table beside the map shows each junction's distance and whether it is final, and the heap is listed under it. Press Next to step, or Play. At a few steps the player stops and asks you to predict.
Dijkstra takes the smallest entry from the heap. That junction is final, and then its roads are relaxed.
Step by step: Dijkstra on the courier map. The animated player loads in your browser.
Look at the finished table. Junction 1 first got 4, from the road 0 to 1. Then junction 2 became final, and the road 2 to 1 gave a better way: 1 + 2 = 3.
The distance of junction 1 was lowered, and the old entry (4, 1) stayed in the heap. It was stale: when it leaves, junction 1 already has 3, so Dijkstra skips it.
To relax a road, add its cost to the distance at its start. If the sum beats the distance at its end, lower it.
The distances are 0, 3, 1, 4, 7 and 8. Junction 5 got 10 first, through the road 1 to 5, then 8 through the road 4 to 5. The cheapest route to it is 8 minutes.
Predict what happens
Q The heap holds (4, 3), (7, 4) and (10, 5). Which entry does Dijkstra take next?
Answer: B
A min-heap always gives out the smallest distance. The order matters a lot: taking the smallest first is what makes its distance final.
Exercise · Predict the output: Distances after the cheaper way is found. Dijkstra runs from junction 0 on five junctions. Junction 1 is first found at 4 minutes, then a cheaper way appears. Unreached junctions would print -1. What does it print?
import heapq
n = 5
edges = [[0, 1, 4], [0, 2, 1], [2, 1, 2], [2, 3, 6], [1, 3, 1], [3, 4, 2]]
graph = [[] for _ in range(n)]
for a, b, minutes in edges:
graph[a].append((b, minutes))
dist = [-1] * n
dist[0] = 0
heap = [(0, 0)]
while heap:
d, node = heapq.heappop(heap)
if d > dist[node]:
continue
for nxt, minutes in graph[node]:
nd = d + minutes
if dist[nxt] == -1 or nd < dist[nxt]:
dist[nxt] = nd
heapq.heappush(heap, (nd, nxt))
print(*dist)Now look at a different map. The road from 2 to 1 has a cost of -3: a credit, such as a promotion for couriers who pick that road. Run Dijkstra on it, and then Bellman-Ford, and compare the answers.
Step by step: Dijkstra with a negative cost. The animated player loads in your browser.
Step by step: Bellman-Ford with a negative cost. The animated player loads in your browser.
Dijkstra ends with junction 1 at 4. The true cheapest way is 0, 2, 1: 5 - 3 = 2. Dijkstra had already called junction 1 final, so when it found the better way, it was too late. Bellman-Ford keeps relaxing every road, round after round, so it finds 2.
Exercise · Break it: The road that pays back. This search picks the closest junction that is not final yet, marks it final and never revisits it. Find a map where its distances are wrong. Costs may be negative.
def distances(n, edges, src):
INF = 1_000_000_000
dist = [INF] * n
dist[src] = 0
final = [False] * n
for _ in range(n):
node = -1
for v in range(n):
if not final[v] and dist[v] < INF and (node == -1 or dist[v] < dist[node]):
node = v
if node == -1:
break
final[node] = True
for a, b, cost in edges:
if a == node and dist[node] + cost < dist[b]:
dist[b] = dist[node] + cost
return distPredict what happens
Q Bellman-Ford runs on a map with four roads and finds nothing to lower in round two. What does it do?
Answer: B
A round that changes nothing means no road can improve any distance. Another round would do the same, so Bellman-Ford stops. A negative cycle shows up the other way: distances still fall in the last possible round.
Now change the costs yourself. Pick a map, change any road's cost, choose the start, and run Dijkstra or Bellman-Ford. Step through forwards and back.
Try these five, in order:
The visualizer: pick a grid or a map, then step through the algorithm on it. It loads in your browser.
Think about the heap at any moment. Every vertex is in one of three groups: final, waiting in the heap with a distance, or not reached yet.
Take the smallest waiting entry, say vertex v with distance 6. Could there be a cheaper way to v? Any other route to v must leave the final vertices through some road. The first vertex on it that is not final is waiting in the heap, so its distance is at least 6, because 6 is the smallest.
The rest of that route can only add more, since no road has a negative cost. So no route to v is cheaper than 6.
The smallest distance waiting in the heap is final: any other way there goes through a waiting vertex that is no closer, and no road is negative. So vertices leave the heap in order of distance.
This is the same idea as BFS. In BFS, vertices leave the queue in order of road count. In Dijkstra, they leave the heap in order of cost. BFS is Dijkstra for the case where every road costs 1.
Predict what happens
Q Why does Dijkstra need a heap, when BFS only needs a queue?
Answer: B
In BFS, the oldest waiting vertex is always the closest one, so a queue is enough. With costs, a vertex found later can have a smaller distance than one found earlier. The heap gives out the smallest every time.
The proof above used one fact: adding a road can never make a distance smaller. With a negative road, a route through a vertex that is still waiting can end up cheaper than the route we called final. Dijkstra never goes back to a final vertex, so it keeps the wrong distance.
The code below has no final flag: it only skips stale entries. On a negative road it does go back, pushing the lowered junction again, and on the small map above that repairs the answer. But each repair can set off more, and on bigger maps the work can grow exponentially. So with negative costs, Dijkstra loses either its correct answer or its speed.
A negative cost breaks Dijkstra: a junction it already called final can get a cheaper way in, and Dijkstra never looks again.
Bellman-Ford does not choose. It relaxes every road, in the listed order. That is one round. After round 1, every distance is at most the cost of the best route that uses one road.
After round 2, it is two roads or fewer. And so on.
A cheapest route never visits a junction twice, so it has at most n - 1 roads. That means n - 1 rounds are always enough, if the map has no negative cycle. A negative cycle is a loop of roads with a total cost below zero. Going round it makes any route cheaper, again and again, so there is no cheapest cost.
After round k, every distance is at most the cost of the best route with k roads or fewer. A cheapest route needs at most n - 1 roads, so a round after that which still lowers a distance means a negative cycle.
Here is Dijkstra as code. It returns the distance from the start to every junction, with -1 for a junction that cannot be reached. The step markers [1] to [5] match the steps in the player.
Python and Java have a built-in heap. JavaScript does not, so its code includes a small one.
import heapq
def dijkstra_distances(n, edges, src):
# [1] Build the adjacency lists: for each junction, the roads that leave it.
graph = [[] for _ in range(n)]
for a, b, minutes in edges:
graph[a].append((b, minutes))
# [2] The start is at 0 and joins the heap; every other junction is not reached yet (-1).
dist = [-1] * n
dist[src] = 0
heap = [(0, src)]
while heap:
# [3] Take the smallest entry: that junction's distance is final.
d, node = heapq.heappop(heap)
# [4] An entry older than the junction's best distance is stale: skip it.
if d > dist[node]:
continue
# [5] Relax each road: a cheaper way to the next junction lowers it and joins the heap.
for nxt, minutes in graph[node]:
nd = d + minutes
if dist[nxt] == -1 or nd < dist[nxt]:
dist[nxt] = nd
heapq.heappush(heap, (nd, nxt))
return distpublic int[] dijkstraDistances(int n, int[][] edges, int src) {
// [1] Build the adjacency lists: for each junction, the roads that leave it.
java.util.List<int[]>[] graph = new java.util.List[n];
for (int i = 0; i < n; i++) graph[i] = new java.util.ArrayList<>();
for (int[] e : edges) graph[e[0]].add(new int[] {e[1], e[2]});
// [2] The start is at 0 and joins the heap; every other junction is not reached yet (-1).
int[] dist = new int[n];
java.util.Arrays.fill(dist, -1);
dist[src] = 0;
java.util.PriorityQueue<int[]> heap = new java.util.PriorityQueue<>((x, y) -> x[0] != y[0] ? Integer.compare(x[0], y[0]) : Integer.compare(x[1], y[1]));
heap.add(new int[] {0, src});
while (!heap.isEmpty()) {
// [3] Take the smallest entry: that junction's distance is final.
int[] top = heap.poll();
int d = top[0], node = top[1];
// [4] An entry older than the junction's best distance is stale: skip it.
if (d > dist[node]) continue;
// [5] Relax each road: a cheaper way to the next junction lowers it and joins the heap.
for (int[] e : graph[node]) {
int nd = d + e[1];
if (dist[e[0]] == -1 || nd < dist[e[0]]) {
dist[e[0]] = nd;
heap.add(new int[] {nd, e[0]});
}
}
}
return dist;
}vector<int> dijkstraDistances(int n, vector<vector<int>> edges, int src) {
// [1] Build the adjacency lists: for each junction, the roads that leave it.
vector<vector<pair<int, int>>> graph(n);
for (auto& e : edges) graph[e[0]].push_back({e[1], e[2]});
// [2] The start is at 0 and joins the heap; every other junction is not reached yet (-1).
vector<int> dist(n, -1);
dist[src] = 0;
priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> heap;
heap.push({0, src});
while (!heap.empty()) {
// [3] Take the smallest entry: that junction's distance is final.
auto [d, node] = heap.top();
heap.pop();
// [4] An entry older than the junction's best distance is stale: skip it.
if (d > dist[node]) continue;
// [5] Relax each road: a cheaper way to the next junction lowers it and joins the heap.
for (auto& [nxt, minutes] : graph[node]) {
int nd = d + minutes;
if (dist[nxt] == -1 || nd < dist[nxt]) {
dist[nxt] = nd;
heap.push({nd, nxt});
}
}
}
return dist;
}function dijkstraDistances(n, edges, src) {
// [1] Build the adjacency lists: for each junction, the roads that leave it.
const graph = Array.from({ length: n }, () => []);
for (const [a, b, minutes] of edges) graph[a].push([b, minutes]);
// [2] The start is at 0 and joins the heap; every other junction is not reached yet (-1).
const dist = new Array(n).fill(-1);
dist[src] = 0;
const heap = [[0, src]];
const less = (x, y) => x[0] < y[0] || (x[0] === y[0] && x[1] < y[1]);
const push = (item) => {
heap.push(item);
let i = heap.length - 1;
while (i > 0 && less(heap[i], heap[(i - 1) >> 1])) {
[heap[i], heap[(i - 1) >> 1]] = [heap[(i - 1) >> 1], heap[i]];
i = (i - 1) >> 1;
}
};
const pop = () => {
const top = heap[0];
const last = heap.pop();
if (heap.length) {
heap[0] = last;
let i = 0;
for (;;) {
let s = i;
const l = 2 * i + 1, r = l + 1;
if (l < heap.length && less(heap[l], heap[s])) s = l;
if (r < heap.length && less(heap[r], heap[s])) s = r;
if (s === i) break;
[heap[i], heap[s]] = [heap[s], heap[i]];
i = s;
}
}
return top;
};
while (heap.length) {
// [3] Take the smallest entry: that junction's distance is final.
const [d, node] = pop();
// [4] An entry older than the junction's best distance is stale: skip it.
if (d > dist[node]) continue;
// [5] Relax each road: a cheaper way to the next junction lowers it and joins the heap.
for (const [nxt, minutes] of graph[node]) {
const nd = d + minutes;
if (dist[nxt] === -1 || nd < dist[nxt]) {
dist[nxt] = nd;
push([nd, nxt]);
}
}
}
return dist;
}The dist list does two jobs. It stores each distance, and -1 also means "not reached yet". A heap entry can be older than dist[node], which is the stale check at marker [4]. Without it, the same junction could be processed again and again.
Exercise · Find the bug: The cheaper way that is ignored. This search keeps the first cost it finds to a junction, even when a cheaper way arrives later. Which line is wrong?
def dijkstra_distances(n, edges, src):
graph = [[] for _ in range(n)]
for a, b, minutes in edges:
graph[a].append((b, minutes))
dist = [-1] * n
dist[src] = 0
heap = [(0, src)]
while heap:
d, node = heapq.heappop(heap)
if d > dist[node]:
continue
for nxt, minutes in graph[node]:
nd = d + minutes
if dist[nxt] == -1 or nd > dist[nxt]:
dist[nxt] = nd
heapq.heappush(heap, (nd, nxt))
return distAnd here is Bellman-Ford. It works with negative costs, so it cannot use -1 for "not reached", because -1 can be a real distance. It uses a large number, a billion, instead. This version assumes the map has no negative cycle.
def bellman_ford(n, edges, src):
# [1] Every distance starts as "not reached" (a billion), except the start at 0.
INF = 1_000_000_000
dist = [INF] * n
dist[src] = 0
# [2] At most n - 1 rounds: a cheapest route uses at most n - 1 roads.
for _ in range(n - 1):
changed = False
# [3] One round: relax every road once, in the listed order.
for a, b, cost in edges:
if dist[a] != INF and dist[a] + cost < dist[b]:
dist[b] = dist[a] + cost
changed = True
# [4] A round that lowers nothing means every distance is final.
if not changed:
break
return distpublic int[] bellmanFord(int n, int[][] edges, int src) {
// [1] Every distance starts as "not reached" (a billion), except the start at 0.
int INF = 1000000000;
int[] dist = new int[n];
java.util.Arrays.fill(dist, INF);
dist[src] = 0;
// [2] At most n - 1 rounds: a cheapest route uses at most n - 1 roads.
for (int round = 0; round < n - 1; round++) {
boolean changed = false;
// [3] One round: relax every road once, in the listed order.
for (int[] e : edges) {
if (dist[e[0]] != INF && dist[e[0]] + e[2] < dist[e[1]]) {
dist[e[1]] = dist[e[0]] + e[2];
changed = true;
}
}
// [4] A round that lowers nothing means every distance is final.
if (!changed) break;
}
return dist;
}vector<int> bellmanFord(int n, vector<vector<int>> edges, int src) {
// [1] Every distance starts as "not reached" (a billion), except the start at 0.
const int INF = 1000000000;
vector<int> dist(n, INF);
dist[src] = 0;
// [2] At most n - 1 rounds: a cheapest route uses at most n - 1 roads.
for (int round = 0; round < n - 1; round++) {
bool changed = false;
// [3] One round: relax every road once, in the listed order.
for (auto& e : edges) {
if (dist[e[0]] != INF && dist[e[0]] + e[2] < dist[e[1]]) {
dist[e[1]] = dist[e[0]] + e[2];
changed = true;
}
}
// [4] A round that lowers nothing means every distance is final.
if (!changed) break;
}
return dist;
}function bellmanFord(n, edges, src) {
// [1] Every distance starts as "not reached" (a billion), except the start at 0.
const INF = 1000000000;
const dist = new Array(n).fill(INF);
dist[src] = 0;
// [2] At most n - 1 rounds: a cheapest route uses at most n - 1 roads.
for (let round = 0; round < n - 1; round++) {
let changed = false;
// [3] One round: relax every road once, in the listed order.
for (const [a, b, cost] of edges) {
if (dist[a] !== INF && dist[a] + cost < dist[b]) {
dist[b] = dist[a] + cost;
changed = true;
}
}
// [4] A round that lowers nothing means every distance is final.
if (!changed) break;
}
return dist;
}To find out whether a negative cycle exists, run one more round after the n - 1 rounds. If any distance still drops, a negative cycle can be reached from the start. To catch a cycle anywhere on the map, start every junction at 0 instead. The warm-up problem Spot a looping discount asks exactly that.
Exercise · Put it in order: Bellman-Ford in rounds. Arrange the lines into Bellman-Ford. It relaxes every road in each of n - 1 rounds, and an unreached junction keeps a billion.
def bellman_ford(n, edges, src):
INF = 1_000_000_000
dist = [INF] * n
dist[src] = 0
for _ in range(n - 1):
for a, b, cost in edges:
if dist[a] != INF and dist[a] + cost < dist[b]:
dist[b] = dist[a] + cost
return dist
for _ in range(n - 2):Predict what happens
Q A map has 5 junctions and no negative cycle. At most how many rounds does Bellman-Ford need?
Answer: B
A cheapest route never visits a junction twice, so with 5 junctions it has at most 4 roads. After round 4, every distance is as low as it can be.
Now write Dijkstra yourself, for a maps app. The lab has one function. Each test gives your function a map as a list of one-way roads, and checks the list of distances it returns.
dijkstra(n, edges, src): return a list of n numbers. The number at position i is the fewest minutes from junction src to junction i, or -1 when junction i cannot be reached. Junction src gets 0.Each road is [from, to, minutes], and every road takes at least 1 minute. When a test fails, the result shows the map, what your function returned and what it should return. A note says what that test is checking.
Three rules keep it correct:
(distance, junction) on the heap, with the distance first, so the heap orders by distance.Build it yourself: write the code in Python, JavaScript, Java or C++ and run the tests. It loads in your browser.
| Question | BFS | Dijkstra with a heap | Bellman-Ford |
|---|---|---|---|
| Time | O(n + m) | O((n + m) log n): each road is relaxed once, and each heap operation costs log n | O(n × m): up to n - 1 rounds over all m roads |
| Memory | O(n + m) | O(n + m) for the lists, the distances and the heap | O(n) for the distances, plus the road list |
| Road costs it handles | Every road costs the same | Never negative | Any, including negative |
| Negative cycle | Not applicable | Gives a wrong answer without warning | Detected by one extra round |
For a map of 100,000 junctions and 200,000 roads, Dijkstra does a few million steps and finishes in well under a second. Bellman-Ford could need 100,000 rounds over 200,000 roads: tens of billions of steps. That is why it is used only when you need negative costs.
Use BFS when the question counts roads or steps, and each step is the same. Use Dijkstra when roads have different costs that are never negative: minutes, kilometres, tolls, risk, network delay. One run gives the cheapest distance to every junction, so the same run also answers "how long until everyone is reached".
Use Bellman-Ford when a cost can be negative, such as a refund, a credit or a gain, or when you need to know whether a loop pays out. Network routing protocols also use its idea: each router tells its neighbours its distances, and everyone keeps lowering their tables.
Do not use Dijkstra when any road can be negative. It will give a wrong answer and no warning. Do not use Bellman-Ford on a big map when costs are not negative: it is far slower than it needs to be.
Also, one run answers one start. For the cheapest route between every pair of junctions on a small map, run it from each junction.
And for one route on a huge road network, real maps add a sense of direction and other tricks on top of Dijkstra.
dist[nxt] = dist[node] + 1 counts roads. On the courier map it says junction 5 is 2 roads from the start, but the cheapest route takes 8 minutes by 5 roads. As soon as roads have different costs, you need Dijkstra.
if nxt == target: return nd returns the first cost found, which may not be the cheapest. On the courier map, junction 5 first gets 10, but its final distance is 8. Stop when the target leaves the heap, not when it joins.
Skip stale heap entries: when an entry leaves the heap with a bigger distance than the junction's best, ignore it.
Without if d > dist[node]: continue, a stale entry such as (4, 1) is processed as if it were new. The answer is still right, but a junction can be expanded many times. On a big map with many cheaper ways found late, the work can grow far past the number of roads.
heapq.heappush(heap, (nd, nxt)) works only while minutes >= 0. With a road of -3, a junction Dijkstra already called final can get a cheaper way in. A version with a final flag never looks again and keeps a wrong distance, and the version above looks again but can redo work many times over. If a cost can be negative, use Bellman-Ford.
dist = [-1] * n is fine in Dijkstra, because every distance is 0 or more. In Bellman-Ford, -1 can be a real distance, such as 3 - 4. Use a large number, such as 1_000_000_000, to mean "not reached", and check dist[a] != INF before adding to it. Adding to the large number would make it look like a real distance.
heapq.heappush(heap, (node, nd)) orders the heap by junction number, not by distance. The algorithm still runs, but a junction can leave the heap before its distance is final. With a final flag the distances come out wrong, and without one the junction is processed again and again. Always put the distance first: (nd, node).
Explain the two algorithms in your own words, then take the checkpoint quiz. The checkpoint counts when you pass both the quiz and the lab.
Explain it back: write the idea in your own words and get feedback.
Checkpoint · Roads with costs
Q1/2 A maps app wants the route with the fewest minutes, and every road has its own travel time. Why is BFS not enough?
Answer: B
BFS treats every road as one step. When roads cost different amounts, the route with the fewest roads is not always the cheapest.
Q2/2 What does Dijkstra keep on its heap?
Answer: A
The heap holds waiting entries as (distance, junction). A min-heap gives out the smallest distance first.
Checkpoint · How Dijkstra moves
Q1/3 Dijkstra takes (3, junction 1) from the heap. What is now true about junction 1?
Answer: B
The smallest waiting distance is final, because any other way in goes through a waiting junction that is no closer, and no road has a negative cost.
Q2/3 Dijkstra relaxes the road from 2 to 1 with cost 2. Junction 2 has distance 1, and junction 1 has distance 4. What happens?
Answer: B
The new distance is 1 + 2 = 3, which beats 4. So the distance is lowered and a new entry goes on the heap. The old entry (4, 1) stays there, stale.
Q3/3 An entry (4, 1) leaves the heap, but junction 1 already has distance 3. What should Dijkstra do?
Answer: B
An entry bigger than the junction's best distance is left over from before a cheaper way was found. Skipping it keeps the work down.
Checkpoint · Negative costs
Q1/3 Why does a road with a negative cost break Dijkstra?
Answer: B
Dijkstra's guarantee depends on a road never lowering a distance. With a negative road, a vertex called final can turn out not to be.
Q2/3 A map has 6 junctions and no negative cycle. At most how many rounds does Bellman-Ford need?
Answer: B
A cheapest route never visits a junction twice, so with 6 junctions it has at most 5 roads, and after round 5 no distance can drop.
Q3/3 Bellman-Ford finishes its n - 1 rounds, and one more round still lowers a distance. What does that mean?
Answer: B
A cheapest route would never need more than n - 1 roads, so a distance that still falls means going round a loop of negative total cost keeps lowering it.
Checkpoint · Costs and mistakes
Q1/2 Which is the cost of Dijkstra with a heap on n junctions and m roads?
Answer: B
Each road is relaxed once and each heap operation costs about log n. Bellman-Ford is the one with O(n × m).
Q2/2 A Dijkstra search for one target returns the first distance it finds for the target, when the target joins the heap. What goes wrong?
Answer: B
On the courier map, junction 5 first gets 10, but its final distance is 8. The smallest entry is final, so wait until the target is the one leaving the heap.
Review cards from this lesson.
Step through the idea on your own input, then build it in the lab. Runs in your browser. Visualiser and lab.
A few questions, then explain the idea back in your own words. Your tutor marks it. Quiz and explain back.