Graph Algorithms

Lesson 17 of 20

Poll the cheapest offer, relax, repeat: Dijkstra locks exact prices from A — then Prim rewires the very same map for a total of 18.

The big picture

Priced graph toolkit

Give every edge a price and graphs start bargain-hunting: Dijkstra settles the exact cheapest route to every hub, while Prim and Kruskal wire the whole map for the least total spend.

Weights change the question

A weight is a price: kilometres, milliseconds, dollars. “Can we reach F?” becomes “what does F cost?” — and here a 15 express cable loses to two cheap hops totalling 14.

Dijkstra’s greedy bet

Settle the cheapest unsettled hub every round — its price can never improve again. Non-negative weights are what make the bet safe.

Relaxation

One comparison drives it all: dist[u] + w < dist[v] means the route through u is cheaper — B fell 7 → 6 through C’s 2-cable, F fell 19 → 14 through E’s 4-cable.

PriorityQueue picks

Java’s min-heap polls the cheapest offer in O(log V). Improvements just push a second offer; stale ones are skipped at poll time. Total: O((V + E) log V).

MST: cheapest wiring

n − 1 edges connecting every hub at least total weight. Prim grows from a seed, Kruskal sorts edges and unions components. Wiring-cheap ≠ travel-cheap: the MST routes A→E in 14, not 10.