Dijkstra on the heap — fill in two holes
In the last step you watched Dijkstra in a table. Now the same thing is written down as an algorithm — and you fill in two missing pieces.
Pseudocode
Dijkstra(from, to):
dist[*] ← ∞; dist[from] ← 0
frontier ← {from at 0}
while frontier is not empty:
v, d ← the CHEAPEST element of frontier // ← the whole point
if done[v]: skip // a stale entry
done[v] ← true
if v = to: return the path and d
for each edge (v → w, cost c):
if d + c < dist[w]:
dist[w] ← d + c
prev[w] ← v
push w onto frontier at d + c
return "no route"
Compare with lesson 14's BFS. Three things differ: a dist array in place of
seen, the condition d + c < dist[w] in place of !seen[w], and the
frontier hands back the cheapest, not the oldest.
The third difference is the only one that needs a structure — and you already have that structure.
Your job
Create three files (see the panel): wgraph.go, wtrails.go and
wgraph_test.go.
wtrails.go— lesson 14's trail generator with one new thing: every edge has a cost, 1–60 days. Complete, not your task.wgraph.go— the skeleton. The last one in the course, and most of it is code already written:WGraphis lesson 14'sGraphwith one field on the edge, andNodeHeapis lesson 13's heap with a different payload. The same array-tree, the same2i+1and(i−1)/2, the same sift-up and sift-down; only what sits in the array changed. Not one new structure.wgraph_test.go— the verdict. For now it checksDijkstraHeaponly.
DijkstraHeap is complete and compiles, but it does not work: the loops are
written and two places are missing. They are marked HOLE 1 and HOLE 2:
- HOLE 1 — the stale entry. In the pseudocode that is
if done[v]: skip. Replacefalsewith a real condition. - HOLE 2 — finding a cheaper route:
if d + c < dist[w]and, inside it, three actions — updatedist, recordprev, and push the node onto the heap again. Delete the_ = ndline — it is only there so the skeleton compiles.
Nothing else needs changing. The loop already contains Pop, done, settled
and rebuild.
The test also checks the table from the last step: 0 → 4 must return the path
[0 2 1 3 4], cost 11, settle 6 nodes and spend 9 units of heap work.
The counter counts frontier work — every comparison the heap makes while
deciding what comes next. It is the only quantity step 6 compares, and it is the
one transit's diagnostics report.
Run the test before you fill anything in
Run it as it stands first:
$ go test ./...
--- FAIL: TestDijkstraHeapReproducesTheTable (0.00s)
wgraph_test.go:97: DijkstraHeap 0 to 4: found=false path=[] cost=0 settled=1 work=0; want path [0 2 1 3 4] cost 11 settled 6 work 9
--- FAIL: TestDijkstraHeapFindsTheCheapestRoute (0.00s)
wgraph_test.go:119: node 2: missed, but the cheapest route costs 213
--- FAIL: TestDijkstraIsWrongOnNegativeWeights (0.00s)
wgraph_test.go:197: no route found at all
FAIL
That is not an error — it is the starting point. The skeleton pops 0, settles
it, pushes nothing (work=0), and the search ends after one node.
Fill in both holes and run it again — you should see ok.
When it does not pass
found=false … settled=1 work=0— nothing entered the heap. Either HOLE 2 is empty, orh.Push(...)is missing, or the comparison is inverted (nd > dist[e.To]lets no cheaper route in).found=false … settled=0— HOLE 1 is inverted: you skip the fresh entries, not the stale ones, so no node is ever settled.path=[4] cost=11, and in the other testthe path does not add up to— the cost is right, but you did not recordprev[e.To] = v, so there is nothing to rebuild the route from.settled=7, when 6 was wanted — HOLE 1 is stillfalse: the stale entry1:4was processed a second time. The answer is right, but the number shows you are doing the work twice.panic: rebuild: the prev[] chain loops—previs overwritten without the conditionnd < dist[e.To]. Every neighbour gets a new parent, settled ones included, and the chain turns into a ring. Thatpanicis a safety valve in the path rebuild: without it the loop would never end.
if v == to is checked on extraction, not on insertion.
Return the route the moment to first enters the queue and you get the first
route found, not the cheapest — a cheaper one may still turn up. In the table,
4:13 entered the heap in the second row and 4:11 only in the fifth. It is
exactly the mistake that marking seen in the wrong place was in lesson 14, only
now it costs correctness rather than route length.
The heap's promise holds at the moment of extraction: only then is it known that nothing cheaper is left.
Stale entries — measured
TestTheHeapHoldsStaleEntries runs the search on your library's network and
counts the pushes:
629 pushes settled 562 nodes: 67 stale entries skipped (1.12 pushes per node)
1.12 pushes per node. If you ever get exactly 1.00, you have implemented decrease-key — a different structure with a different cost, and the test will tell you.
The one limit Dijkstra has
In step 2 the proof rested on an assumption: no edge is negative. Here is what happens without it. The last test shows it:
0 ──1── 2 the direct route, cost 1
0 ──2── 1 ──(−5)── 2 the detour, cost 2 + (−5) = −3
Dijkstra answered 1; the true cheapest route costs -3
Node 2 is reached at 1 and settled before node 1 is popped at all — so the cheaper detour is never considered.
There is no error message, no loop, no slowness. Simply a wrong answer, delivered with exactly the same confidence as a right one. In lesson 11 the degenerate tree was slow and correct; here it is the other way round.
The test requires it to stay that way — so nobody "fixes" Dijkstra by pretending it works with negative costs. There are other algorithms for that (Bellman–Ford), and they cost more.