Sub topic 3
Prim's Algorithm: Growing a Single Tree from a Start Vertex
This chapter assumes you know the cut property, Kruskal's algorithm, and how a binary heap supports push and pop in O(log n) time.
How Prim's Algorithm Works
Prim's algorithm grows one tree, starting from a single vertex. At each step it adds the lightest edge that connects the tree to a vertex outside it. That edge is the lightest edge crossing the cut between the tree and the rest of the graph, so the cut property says it is safe to add.
The lazy version below pushes every edge it finds onto a heap. When it pops an edge whose endpoint is already in the tree, it skips that edge.
import heapq
def prim(adj, start=0):
n = len(adj)
visited = [False] * n
heap = [(0, start, -1)] # (edge weight, vertex, parent)
total, mst = 0, []
while heap:
w, v, parent = heapq.heappop(heap)
if visited[v]:
continue # stale entry
visited[v] = True
total += w
if parent != -1:
mst.append((parent, v, w))
for u, wu in adj[v]:
if not visited[u]:
heapq.heappush(heap, (wu, u, v))
return total, mst
edges = [(1, 0, 1), (4, 0, 2), (3, 1, 2), (2, 1, 3), (5, 2, 3)]
adj = [[] for _ in range(4)]
for w, u, v in edges:
adj[u].append((v, w))
adj[v].append((u, w))
print(prim(adj)) # (6, [(0, 1, 1), (1, 3, 2), (1, 2, 3)])Running Time and Choosing an Algorithm
| Algorithm | Time | Best fit |
|---|---|---|
| Kruskal | O(E log E) = O(E log V) | Sparse graphs, or graphs given as edge lists |
| Prim, binary heap | O(E log V) | Sparse or medium graphs stored as adjacency lists |
| Prim, array scan | O(V²) | Dense graphs, where E is close to V² |
A common mistake is to assume the lazy heap stays small. It can hold up to E entries, and that is why its bound is O(E log V).
Disconnected Graphs
If the graph is disconnected, Prim's algorithm only spans the component that contains start. To get a minimum spanning forest, restart Prim from every vertex that is still unvisited. Kruskal's algorithm produces the forest without any changes, as long as you don't stop it early at V−1 edges.
When Is the MST Unique?
If all edge weights are distinct, the MST is unique. Tied weights can allow more than one MST, but every MST still has the same total weight.
Applications
- Network design: connect sites with cable, pipe, or road at the lowest total cost.
- Single-linkage clustering: run Kruskal's algorithm and stop after V−k edges. The components that remain are k clusters, and the gap between clusters is as large as possible.
Exercise
Prim's algorithm runs on a graph with two components, starting at vertex 0. What does it return, and how do you fix it?
Show answer
It returns the MST of vertex 0's component only. To fix it, loop over all vertices and start Prim again from each one that is still unvisited. The result is a minimum spanning forest.