Graph Algorithms

Lesson 17 of 20

Race 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

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.