Graph Algorithms
Lesson 17 of 20Race a min-heap across weighted links to settle cheapest paths, then grow Prim’s cable tree one greedy edge at a time.
The big picture
Weighted graphs need more than hop counting: settle the cheapest node first, relax its edges, and let a min-heap do the sorting for you.
Weights change everything
BFS counts hops; a weighted map needs cheapest totals. A 2-hop route costing 2 + 7 = 9 can lose to three cheap hops.
Dijkstra’s bet
The smallest unfinished distance is already final — settle that node, relax its edges, repeat until the heap is dry.
heapq is the engine
A Python min-heap pops the cheapest (dist, node) tuple in O(log V); beaten, stale entries get skipped by a done check.
Relaxation
dist[v] = min(dist[v], dist[u] + w) — one line that lets better paths overwrite worse guesses, e.g. 3 + 1 = 4 beats 6.
MST in one sentence
Pick V − 1 edges linking every node at minimum total weight — Prim grows one tree; Kruskal sorts all edges.
The fine print
Negative weights break Dijkstra’s settlement guarantee — a shorter total can appear after a node settles. That is Bellman-Ford territory.
Dijkstra live
Green = settled (final cost), amber = frontier. The heap always pops the cheapest unfinished node.
Five routers, weighted links. Mission: cheapest cost from A to every node. dist = {A: 0}, heap = [(0, A)] — everything else unknown.
Dijkstra pipeline
Every pass of the while-loop runs the same four beats — pop, settle, relax, repeat.
heapq walkthrough
Dijkstra popping cheapest-first, then Prim collecting the minimum spanning tree — both on heapq.
1import heapq2graph = {3'A': [('B', 2), ('C', 5)],4'B': [('C', 1), ('D', 4)],5'C': [('D', 1)],6'D': [],7}8dist = {'A': 0}9done = set()10heap = [(0, 'A')]1112while heap:13d, u = heapq.heappop(heap)14if u in done:15continue16done.add(u)17for v, w in graph[u]:18if v not in dist or d + w < dist[v]:19dist[v] = d + w20heapq.heappush(heap, (dist[v], v))2122print(sorted(dist.items()))
The weighted adjacency dict: each edge is a (neighbor, weight) tuple. A ships to B at cost 2 and C at cost 5.
Prim grows the MST
Same five routers, new mission: link them all with least total cable. Tree edges go green, redundant ones fade.
Same network as the Dijkstra run — new question: connect all five nodes with minimum total weight. Prim grows one tree from A; frontier edges are amber.
Predict the output
Three heapq moves — tuples compare left to right.
1import heapq23heap = [(2, 'B'), (1, 'A'), (3, 'C')]4heapq.heapify(heap)5d, node = heapq.heappop(heap)6heapq.heappush(heap, (0, node))7d2, node2 = heapq.heappop(heap)89print(node, d)10print(node2, d2)11print(heap[0])
Hint: heapify orders by the first tuple element; ties break on the second. Re-pushing a better distance leaves the old entry inside — the stale one Dijkstra must skip.
Concept check
Click a term, then click its meaning to lock the pair.
Key takeaways
Dijkstra = settle the cheapest unfinished node, relax its edges, repeat — heapq pops in O(log V).
dist[v] = min(dist[v], dist[u] + w): the one line that lets better paths overwrite worse guesses.
Stale heap entries are normal — the done check skips them; never settle a node twice.
BFS counts hops, Dijkstra counts cost — on an unweighted graph the two agree exactly.
MST = V − 1 edges at minimum total weight: Prim grows a tree, Kruskal sorts all edges.
Negative weights void Dijkstra’s guarantee — reach for Bellman-Ford instead.