Graph Algorithms
Lesson 17 of 20Poll the cheapest offer, relax, repeat: Dijkstra locks exact prices from A — then Prim rewires the very same map for a total of 18.
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.
Dijkstra settles prices
Green = settled at a final price, amber = frontier offer. Watch two prices improve and two stale offers get skipped.
A priced network — each number is a cable cost. Dijkstra starts at A: dist 0; every other hub sits at ∞.
The poll–relax loop
One lap of the while loop — poll, settle, stale-check, relax — until the heap drains.
Walkthrough
Dijkstra with a PriorityQueue over the priced map — then lazy Prim costing the MST on the very same graph.
1import java.util.*;23public class Dijkstra {4public static void main(String[] args) {5int[][][] adj = { {{1,7},{2,4}}, {{0,7},{2,2},{3,5}}, {{0,4},{1,2},{4,6},{5,15}},6{{1,5},{4,3}}, {{2,6},{3,3},{5,4}}, {{2,15},{4,4}} };7int n = 6, src = 0, INF = 1000000;8int[] dist = new int[n];9Arrays.fill(dist, INF);10dist[src] = 0;11boolean[] done = new boolean[n];12PriorityQueue<int[]> pq = new PriorityQueue<>((a, b) -> a[1] - b[1]);13pq.add(new int[]{src, 0});14while (!pq.isEmpty()) {15int u = pq.poll()[0];16if (done[u]) continue;17done[u] = true;18for (int[] e : adj[u])19if (dist[u] + e[1] < dist[e[0]]) {20dist[e[0]] = dist[u] + e[1];21pq.add(new int[]{e[0], dist[e[0]]});22}23}24for (int i = 0; i < n; i++)25System.out.print((char) ('A' + i) + "=" + dist[i] + " ");26}27}
Six hubs, source A (index 0), INF = 1000000 playing ∞. Above sits the weighted adjacency list — every entry is {neighbor, cost}.
Prim wires the MST
One tree, five cables, total 18 — the cheapest way to link every hub on the map.
Same priced map, new mission: link all six hubs for the least TOTAL cable. Prim grows one tree from A.
Predict the output
A compact four-hub Dijkstra — no settled set, just improve-or-skip. What prints?
1import java.util.*;23public class Predict {4public static void main(String[] args) {5int[][][] adj = { {{1,10},{2,3}}, {{3,4}}, {{1,2},{3,9}}, {} };6int[] dist = {0, 1000000, 1000000, 1000000};7PriorityQueue<int[]> pq = new PriorityQueue<>((a, b) -> a[1] - b[1]);8pq.add(new int[]{0, 0});9while (!pq.isEmpty()) {10int u = pq.poll()[0];11for (int[] e : adj[u])12if (dist[u] + e[1] < dist[e[0]]) {13dist[e[0]] = dist[u] + e[1]; pq.add(new int[]{e[0], dist[e[0]]});14}15}16System.out.println("B=" + dist[1] + " C=" + dist[2] + " D=" + dist[3]);17}18}
Hint: C polls at 3 before B’s 10-offer can win: 3+2 = 5 beats 10 into B, then 5+4 = 9 beats 12 into D. The 10-cable into B never improves anything.
Concept check
Click a term, then click its meaning to lock the pair.
Key takeaways
Dijkstra = greedy pick + relaxation: settle the cheapest unsettled hub, then try to improve its neighbors.
dist[u] + w < dist[v] is the whole algorithm — 4+2 = 6 beating 7 is relaxation in action.
Non-negative weights are mandatory: one negative edge can retroactively break a settled distance.
The PriorityQueue hands you the cheapest offer in O(log V); stale entries are skipped at poll time, not deleted.
Prim grows the cheapest crossing cable each round (total 18 here); Kruskal sorts all edges and unions components.
MST ≠ shortest-path tree: the MST drops C–E (6) for D–E (3), so A→E over the tree costs 14, not 10.