Week 14, Monday — Prim’s Algorithm
April 8, 2026

You can pave road segments. Each segment costs its number of paving stones.
Goal: pave the __________ stones so every house can reach every other.
Which roads do you pave?
How many stones total?
Input: connected, undirected graph \(G\) with edge weights
Output: subgraph \(G'\) such that:
What is the MST of this graph?
Total weight = ____
Partition Property (Cut Property)
Split vertices into any two sets \(S\) and \(V \setminus S\).
The minimum-weight edge crossing the cut is always in some MST.
Initialize structure:
v: d[v] = INF, p[v] = nulld[s] = 0d[v]Repeat n times:
d[] unlabelled vertex: vvw of v:
wt[(v,w)] < d[w])
d[w] = wt[(v,w)]p[w] = vWhere is the solution?
Initialize structure:
v: d[v] = INF, p[v] = nulld[s] = 0d[v]Repeat n times:
d[] unlabelled vertex: vvw of v:
wt[(v,w)] < d[w])
d[w] = wt[(v,w)]p[w] = vReturn p
What design choices do we need to make?
Put a ⭐ by __________________ operations.
Put a 💜 by __________________ operations.
Initialize structure:
v: d[v] = INF, p[v] = nulld[s] = 0d[v] ⭐Repeat n times:
d[] unlabelled vertex: v ⭐vw of v: 💜
wt[(v,w)] < d[w])
d[w] = wt[(v,w)] ⭐p[w] = vReturn p
⭐ \(n\) removeMins + \(\leq m\) decreaseKeys
💜 \(O(m)\) total (adj list) | \(O(n^2)\) total (adj matrix)
| Adj matrix | Adj list | |
|---|---|---|
| heap | \(O(n^2 + m \log n)\) | \(O(m \log n)\) |
| unsorted array | \(O(n^2)\) | \(O(n^2)\) |
Which is best? Depends on graph density:
import heapq
def prim(graph, start):
"""graph: {vertex: [(neighbor, weight), ...]}"""
d = {v: float('inf') for v in graph} # cheapest edge to reach v
parent = {v: None for v in graph}
d[start] = 0
pq = [(0, start)] # (edge_weight, vertex)
visited = set()
while pq:
cost, v = heapq.heappop(pq)
if v in visited:
continue
visited.add(v)
for w, weight in graph[v]:
if w not in visited and weight < d[w]:
d[w] = weight # just the edge weight (not cumulative!)
parent[w] = v
heapq.heappush(pq, (weight, w))
return parent # MST as parent pointersGiven a start vertex (source) \(s\), find the path of least total cost from \(s\) to every vertex in the graph.

Dijkstra’s Algorithm (1959)
Note:

Given a source vertex \(s\), we wish to find the shortest path from \(s\) to every other vertex in the graph.
Initialize structure:
d:p:Repeat these steps:
Initialize structure:
v: d[v] = INF, p[v] = nulld[s] = 0d[v]Repeat n times:
d[] unlabelled vertex: vvw of v:
d[w])
d[w] = ________________p[w] = vReturn p

When a node becomes labeled, its shortest distance is final. It will never improve again.
d[] values only decrease, never increase.
The predecessors p[] form a shortest-path tree.
Execute Dijkstra’s algorithm on this graph: