Dijkstra & Smooth Radio
In short: once edges carry different weights, BFS's "found first" no
longer means "cheapest" — a one-hop jump can cost more than a three-hop
chain. Dijkstra's algorithm fixes that with one rule: always settle
the reachable-but-unsettled vertex with the cheapest known cost next, and
relax its edges (lower a neighbour's cost if going through here beats
what you knew). With a binary heap (heapq), that's O((V + E) log V)
time and O(V + E) space — the extra log factor buys the ability to handle
real-world costs, not just hop counts. It only works with non-negative
weights; negative edges need Bellman-Ford, O(V × E).

Smooth radio's cheapest crossfade chain
Smooth radio gets you from one song to another without a jarring jump. Every crossfade has a cost, and the station should play the chain with the lowest total cost — even if that means extra songs on the way:
BFS would happily return the one-step jump costing 9. The three-step chain costs 3 — fewest edges and cheapest total are different questions. Watch the settled region grow outward, cheapest first; each badge is the best cost known so far:
Dijkstra settles songs in order of cost, and a settled cost is final.
Intro costs nothing to reach, so it settles first at 0. 5 nodes, 6 edges, undirected. At intro. Settled: intro. intro: 0.
"Give me the cheapest one" is a job for a priority queue — heapq. Push
(cost, song) tuples; heappop always returns the smallest:
import heapq
heap = []
heapq.heappush(heap, (5, "glow"))
heapq.heappush(heap, (2, "drift"))
heapq.heappush(heap, (2, "aura"))
print(heapq.heappop(heap))Two rounds of relaxation — asking "is going through here cheaper than what I know?" — in slow motion:
Put pop-cheapest and relax together. A song can sit in the heap more than once — an old, pricier entry a later improvement left behind — so skip entries that are stale:
Watch that function draw itself — change a weight and run it again:
Your Dijkstra: badges only ever go down, and a song's badge is final once it settles.
The mistake: treating a cost as final the moment it's pushed instead of when it's popped. Drift locks in at 9 here before glow ever gets a chance to offer the cheaper route through it:
The cheapest chain is intro → glow → drift, costing 3, but this prints 9. Fix it so a later, cheaper route can still win.
Exactly like BFS, a parent dict gives you the chain, not just the cost —
but update it every time you relax, because a song's best predecessor can
change mid-search: