Skip to the workspace
Pebellslearn by building
Graphs  ›  Lesson

Dijkstra & Smooth Radio

Shortest Paths 24 minAlways settle the cheapest place next

dsa / Dijkstra & Smooth Radio

Explore each scene at your own pace.

01 · Smooth radio's cheapest crossfade chain

Smooth radio's cheapest crossfade chain

Dijkstra & Smooth Radio

Definition
Dijkstra's algorithm finds the cheapest route from one vertex to all others in a graph whose edges have non-negative costs, by repeatedly settling the unsettled vertex with the lowest known cost and lowering its neighbours' costs where it helps.
In plain words
It is like planning the cheapest journey when every leg has a price: you always lock in the cheapest place you can currently reach, then check whether going on from there makes any other place cheaper. A longer trip of small hops can beat one expensive jump.

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).

A map where intro is settled at cost 0, glow at 1, aura at 2 and drift at 3 — reached the long way through glow and aura — while the direct 9-cost jump from intro to drift stays unsettled, beaten by 1+1+1

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:

python

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:

watch it move · graph

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.

1 / 8

"Give me the cheapest one" is a job for a priority queue — heapq. Push (cost, song) tuples; heappop always returns the smallest:

What does this print?
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:

step through it
1inf = float("inf")
2dist = {"intro": 0, "glow": inf, "drift": inf}
3out = {"intro": [("drift", 4), ("glow", 1)], "glow": [("drift", 2)]}
4for song in ["intro", "glow"]:
5 for nxt, step in out[song]:
6 if dist[song] + step < dist[nxt]:
7 dist[nxt] = dist[song] + step
8print(dist)

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:

python

Watch that function draw itself — change a weight and run it again:

your code, drawn · graph

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:

broken — fix 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:

python
Scene 1 of 6
Project context and further resources
You're building a piece ofTunebox — recommendations
This piece — smoothest_mix(): The cheapest chain of transitions between two songs.
Scenario Smooth radio takes you from the song you're on to the one you asked for without a jarring key change. Each crossfade has a cost, and the station plays the cheapest chain.
smoothest_mix.py
Call the function you wrote — just like your app's frontend would. Edit the inputs and hit Call.
smoothest_mix(transitions, start, goal) → dictThe cheapest chain of transitions as {cost, path}; cost -1 and an empty path if unreachable.
try:
returned
Press Run to execute your code.
Press Check to run the tests for this lesson.
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.