Prim's Algorithm: Growing a Minimum Spanning Tree
Learn Prim's algorithm for finding minimum spanning trees starting from a vertex, using a greedy approach with priority queues.
Prim's algorithm finds a minimum spanning tree of a connected, undirected, weighted graph by repeatedly adding a light edge across the current tree's cut. Complexity depends on representation: the lazy binary heap shown here runs in O(E log E), while an adjacency matrix with a linear scan takes O(V²). The matrix approach is often simpler and competitive on dense graphs. Ties can produce different valid edge sets, so correctness checks compare total MST weight.
Prim’s Algorithm: Growing a Minimum Spanning Tree
Like Kruskal’s, Prim’s algorithm finds a Minimum Spanning Tree—but it grows a single tree from a chosen starting vertex rather than building a forest. At each step, Prim’s adds the cheapest edge that connects the current tree to an outside vertex. This “growing tree” approach makes Prim’s particularly natural for dense graphs and those represented as adjacency matrices.
The algorithm maintains a priority queue of edges crossing the cut between visited and unvisited vertices, always picking the minimum-weight crossing edge.
Introduction
Prim’s algorithm finds a minimum spanning tree (MST) in a connected, undirected, weighted graph. Starting at any vertex, it repeatedly adds a minimum-weight edge from the current tree to a vertex outside it. The cut property makes that choice safe: a lightest edge crossing a cut belongs to some MST.
The implementation below expects vertices numbered 0 through V - 1 and an adjacency list that records each undirected edge in both directions. It returns no MST when the graph is disconnected. Negative weights are allowed, and tied edge weights can produce different MST edge sets with the same minimum total weight.
The right implementation depends on how the graph is stored and how the priority queue works. The lazy heap in this guide can hold stale edge entries; its bound differs from an indexed heap with decrease-key. For a dense graph already stored as a matrix, a linear scan is often simpler and avoids heap operations.
Basic Implementation
import heapq
from collections import defaultdict
def prim_mst(graph, start=0):
"""
Prim's algorithm for Minimum Spanning Tree.
Args:
graph: Adjacency list {u: [(v, weight), ...]}
start: Starting vertex
Returns (mst_edges, total_weight), or None if disconnected.
"""
n = len(graph)
if n == 0 or start < 0 or start >= n:
raise ValueError("graph must be non-empty and start must be a valid vertex")
visited = [False] * n
min_heap = [] # (weight, u, v)
visited[start] = True
# Add all edges from start vertex
for neighbor, weight in graph[start]:
heapq.heappush(min_heap, (weight, start, neighbor))
mst_edges = []
total_weight = 0
while min_heap and len(mst_edges) < n - 1:
weight, u, v = heapq.heappop(min_heap)
if visited[v]:
continue # Skip if already in MST
# Add edge to MST
mst_edges.append((u, v, weight))
total_weight += weight
visited[v] = True
# Add edges from newly added vertex
for neighbor, w in graph[v]:
if not visited[neighbor]:
heapq.heappush(min_heap, (w, v, neighbor))
if len(mst_edges) != n - 1:
return None # No spanning tree exists for a disconnected graph.
return mst_edges, total_weight
Dense Graph Implementation
For a connected graph represented by a symmetric adjacency matrix, a linear scan selects the next vertex in O(V) per step and scans a row for updates. The total is O(V²), with O(V²) space for the matrix. Use None for a missing edge so zero and negative weights remain valid:
def prim_mst_dense(num_vertices, graph):
"""
Prim's algorithm with O(V²) using adjacency matrix.
Better for dense graphs.
Args:
num_vertices: Number of vertices
graph: symmetric matrix; None means no edge, any number is an edge weight
Returns (mst_edges, total_weight), or None if disconnected.
"""
if num_vertices <= 0:
raise ValueError("graph must contain at least one vertex")
in_mst = [False] * num_vertices
min_edge = [float('inf')] * num_vertices
parent = [-1] * num_vertices
# Start from vertex 0
min_edge[0] = 0
mst_edges = []
total = 0
for _ in range(num_vertices):
# Find minimum vertex not yet in MST
u = -1
min_weight = float('inf')
for v in range(num_vertices):
if not in_mst[v] and min_edge[v] < min_weight:
min_weight = min_edge[v]
u = v
if u == -1 or min_weight == float('inf'):
return None # The remaining vertices are unreachable.
in_mst[u] = True
if parent[u] != -1:
mst_edges.append((parent[u], u, min_weight))
total += min_weight
# Update minimum edges for adjacent vertices
for v in range(num_vertices):
weight = graph[u][v]
if not in_mst[v] and weight is not None and weight < min_edge[v]:
min_edge[v] = weight
parent[v] = u
return mst_edges, total
When to Use Prim’s Algorithm
Use Prim’s when:
- You have a connected, undirected, weighted graph and need an MST
- The graph is dense or already stored as an adjacency matrix
- You want to grow a tree one edge at a time
Don’t use Prim’s when:
- The graph is very sparse and Kruskal’s with union-find fits the representation better
- The graph is disconnected and you need a minimum spanning forest directly; Prim’s can produce one by restarting at each unvisited vertex
- You only need approximate MST (though both are exact)
The O(V²) matrix version is often the practical choice when E is close to V² or the input already comes as a matrix. It uses O(V²) space, but avoids heap bookkeeping and has predictable access patterns. For sparse graphs, an adjacency list with a heap usually avoids scanning all V² possible edges.
Trade-off Analysis
| Prim’s representation / queue | Time | Extra space (besides graph) | Notes |
|---|---|---|---|
| Adjacency list + lazy binary heap (code above) | O(E log E), often O(E log V) for simple graphs | O(E) heap entries | Stale edges remain until popped |
| Adjacency list + indexed binary heap with decrease-key | O((V + E) log V) | O(V) queue entries | One best key per vertex |
| Adjacency list + Fibonacci heap | O(E + V log V) amortized | O(V) queue entries | Better asymptotic decrease-key bound; higher implementation cost |
| Adjacency matrix + linear scan | O(V²) | O(V) auxiliary | Matrix itself uses O(V²) space |
For comparison, Kruskal’s with comparison sorting takes O(E log E), plus near-linear disjoint-set operations. These bounds assume the graph is represented as stated; the lazy heap in the first implementation pushes edges, while the indexed heap updates one key per vertex.
Production Failure Scenarios
- Disconnected graph: A single run visits only the component containing its start vertex. The implementation returns
Nonewhen it cannot reach all vertices; restart from each unvisited vertex if you need a minimum spanning forest. - Large dense graphs: O(V²) memory for adjacency matrix can be prohibitive—use adjacency list with heap
- Integer overflow: When summing edge weights, ensure appropriate data types
Complete Example
def solve():
# Example graph as adjacency list
graph = {
0: [(1, 10), (3, 5)],
1: [(0, 10), (2, 1), (3, 3)],
2: [(1, 1), (3, 9), (4, 4)],
3: [(0, 5), (1, 3), (2, 9), (4, 2)],
4: [(2, 4), (3, 2)]
}
mst, weight = prim_mst(graph, start=0)
print(f"MST total weight: {weight}")
print("Edges in MST:")
for u, v, w in mst:
print(f" {u} -- {v}: {w}")
Correctness Check
This small check includes a negative edge and equal-weight alternatives. It checks that Prim’s returns V - 1 edges with the expected total weight; it does not require one exact edge list because a tied graph can have several valid MSTs.
def check_prim_mst():
graph = {
0: [(1, -2), (2, 1)],
1: [(0, -2), (2, 1), (3, 2)],
2: [(0, 1), (1, 1), (3, 2)],
3: [(1, 2), (2, 2)],
}
result = prim_mst(graph, start=0)
assert result is not None
edges, total_weight = result
assert len(edges) == 3
assert total_weight == 1
disconnected = {0: [(1, 4)], 1: [(0, 4)], 2: []}
assert prim_mst(disconnected, start=0) is None
Quick Recap Checklist
- Start from any vertex (or specified start)
- Maintain priority queue of crossing edges
- Always add minimum-weight edge connecting visited to unvisited
- Continue until V-1 edges or queue empty
- Return no MST for a disconnected input; restart per component if a forest is needed
- Choose heap for sparse, matrix for dense graphs
Interview Questions
A cut separates vertices into two non-empty sets. The cut property states: for any cut, the minimum-weight edge crossing that cut belongs to some minimum spanning tree. Prim's repeatedly applies this by maintaining a cut between visited and unvisited vertices—at each step, the minimum crossing edge must be in the MST, so adding it is always safe.
Prim's and Dijkstra's look identical in implementation but differ fundamentally in goal. Both use a priority queue to pick minimum-weight crossing edges. Dijkstra's selects the minimum-distance vertex from source and accumulates path distances. Prim's selects the minimum crossing edge to any unvisited vertex regardless of source. The difference: Prim's doesn't accumulate distances or care about which vertex you started from—it's building a tree that spans all vertices.
Yes. The starting vertex can change which equal-weight edges are selected, but every MST of the same graph has the same minimum total weight. When edge weights tie, the edge set itself need not be unique.
Choose the O(V²) matrix version of Prim's when the graph is dense or already stored as a matrix; it scans all possible pairs and avoids heap bookkeeping. For sparse adjacency lists, heap-based Prim's or Kruskal's usually does less work. The starting vertex does not change the minimum total weight.
The bound depends on both graph representation and queue:
- Lazy binary heap with adjacency list: O(E log E), often O(E log V) for simple graphs; stale edge entries remain in the heap
- Indexed binary heap with decrease-key: O((V + E) log V)
- Fibonacci heap with adjacency list: O(E + V log V) amortized
- Adjacency matrix with linear scan: O(V²), a practical choice for dense graphs
Yes. Prim's works with negative edge weights because each step chooses a lightest edge crossing the cut; edge signs do not change that argument. A connected, undirected, weighted graph still has an MST even if it contains negative-weight edges. If weights tie, more than one edge set may achieve the same minimum total weight.
For a single MST, the graph must be connected. The heap code returns None if it visits fewer than V vertices, which means the start vertex cannot reach the whole graph. To build a minimum spanning forest instead, restart Prim's from each unvisited vertex and combine the component trees.
- Check that the result contains exactly V - 1 edges
- Return a clear disconnected result rather than an incomplete tree or infinite weight
- To return a forest, start a new run from each vertex that remains unvisited
Prim's algorithm is used in various real-world applications:
- Network design: Laying fiber-optic cable, electrical grids, or water pipes at minimum cost while connecting all nodes
- Transportation: Building roads or railway networks connecting cities with minimum total construction cost
- Cluster analysis: Constructing minimum spanning trees for hierarchical clustering
- Approximation algorithms: Used as a subroutine in approximation algorithms for NP-hard problems like the Traveling Salesman Problem
Both versions follow the same greedy principle but differ in how they manage the priority queue:
- Lazy Prim's: Pushes all crossing edges onto the heap without removing stale entries. When popping, it skips edges leading to already-visited vertices. Simpler to implement but the heap can grow to O(E) size.
- Eager Prim's: Maintains a fixed-size array of best-known distances and supports decrease-key operations. Only the best edge to each unvisited vertex is kept in the priority queue, keeping heap size at O(V). Requires a data structure that supports decrease-key efficiently.
Prim's algorithm is designed for undirected graphs because it relies on the cut property, which assumes edges are symmetric. In a directed graph, the minimum-weight edge crossing a cut might not be usable in both directions when building a tree. Finding a minimum spanning arborescence (the directed equivalent) requires a different algorithm, such as Edmonds' algorithm (Chu–Liu/Edmonds).
The starting vertex does not affect the minimum MST weight, but it can change the order of work and the selected edges when weights tie. The edge set can differ while its total remains the same. Not every spanning tree has the same weight; this guarantee applies to minimum spanning trees.
Yes, Prim's is naturally iterative—the priority queue loop is the core, not recursion. There's no need for recursive calls since the algorithm repeatedly extracts the minimum crossing edge until the MST is complete. Watch out for stack overflow in recursive implementations of other graph algorithms (like DFS), but Prim's main loop is straightforward iteration. The only consideration is ensuring the heap operations (push/pop) are correctly managed.
To find a maximum spanning tree, simply reverse the comparison in the priority queue—instead of always extracting the minimum crossing edge, extract the maximum. This means using a max-heap, or equivalently, negating all edge weights and using a min-heap. The cut property still holds for maximums: the maximum-weight edge crossing any cut belongs to some maximum spanning tree. This modification is trivial and often used in network design where maximum reliability or bandwidth matters.
The visited array tracks which vertices have been added to the MST, enforcing the cut between visited (in the tree) and unvisited (outside the tree) sets. Without it, the algorithm might select edges that connect two vertices already in the MST, violating the tree property. When popping an edge from the heap, you check if visited[v]: continue to skip stale entries in lazy Prim's. This array is also used to detect disconnected graphs—if fewer than V-1 edges are added, not all vertices were reachable.
BFS and DFS are uninformed traversals—they explore vertices based on discovery order rather than edge weights. Prim's is a weighted traversal: it always picks the minimum-weight crossing edge, making it a greedy algorithm with a specific optimization goal (minimum spanning tree). BFS finds shortest paths in unweighted graphs; Prim's finds minimum-cost trees in weighted graphs. Both maintain visited sets, but Prim's uses a priority queue where DFS uses a stack and BFS uses a queue.
Lazy Prim's is simpler to implement, but it can hold O(E) heap entries. Eager Prim's keeps O(V) queue entries but needs decrease-key bookkeeping. Neither is always faster; choose based on graph size and memory limits, then measure on your workload.
To find a minimum spanning forest, run Prim's from an unvisited vertex after each component run completes. Continue until every vertex has been visited; each run contributes one component's MST. The single-tree function shown above instead returns None for a disconnected graph.
For large graphs, several optimizations help:
- Adjacency list over matrix—O(V+E) vs O(V²) space, critical for sparse graphs with millions of vertices
- Lazy Prim's heap pruning—skip stale entries with visited checks instead of maintaining exact entries
- Bit arrays for visited—use Python's
bytearrayorarray('b')for compact visited tracking - Streaming edge reads—for graphs too large to fit in memory, read edges in batches and process incrementally
Prim's handles parallel edges correctly—both edges will be pushed to the heap, and the algorithm will naturally pick the lighter one when its endpoint becomes reachable. The presence of parallel edges doesn't break correctness; it just means the heap may contain multiple entries for the same vertex pair. The visited check ensures only one edge per vertex join is used in the final MST. Ensure your graph representation distinguishes parallel edges (e.g., keep multiple weight entries in the adjacency list).
Yes—a minimum spanning forest is simply multiple MSTs for disconnected graph components. Run Prim's normally; if it finishes with fewer than V-1 edges, the graph was disconnected. To find the full forest, track visited vertices and when the algorithm ends, find the first unvisited vertex, start a new Prim's from there, and repeat until all vertices are covered. Each run produces one component's MST. This approach is equivalent to running Kruskal's on a disconnected graph—the result is a forest rather than a single tree.
Further Reading
- CLRS Introduction to Algorithms (Chapter 23) – Covers Prim’s and Kruskal’s with rigorous proofs of the cut property and optimal substructure for minimum spanning trees.
- The Algorithm Design Manual by Steven Skiena – Offers practical guidance on selecting between Prim’s and Kruskal’s with real-world graph examples.
- Priority Queues and Binary Heaps – Queue operations determine the heap-based version’s complexity; the lazy heap shown above takes O(E log E).
- Fibonacci Heaps – For advanced readers, Prim’s achieves O(E + V log V) with Fibonacci heaps, the theoretical best for sparse graphs.
- Adjacency Matrix vs Adjacency List – How the choice of graph representation affects Prim’s performance and memory footprint.
- Related Content:
Conclusion
Prim’s algorithm grows an MST one vertex at a time, always adding the cheapest edge from the visited set to an unvisited vertex. Use the heap version for sparse graphs and the O(V²) matrix version for dense ones. Like Kruskal’s, it relies on the cut property—each minimum crossing edge is always safe to add.
Category
Related Posts
Kruskal's Algorithm: Building Minimum Spanning Trees
Learn Kruskal's algorithm for finding minimum spanning trees in weighted graphs using union-find data structures.
Bellman-Ford Algorithm: Shortest Paths with Negative Weights
Learn the Bellman-Ford algorithm for single-source shortest paths including negative edge weights and negative cycle detection.
Dijkstra's Algorithm: Finding Shortest Paths in Weighted Graphs
Learn Dijkstra's algorithm for single-source shortest paths in graphs with non-negative edge weights, including implementations and trade-offs.