Prim's Algorithm
Prim's algorithm builds a minimum spanning tree by growing one tree outwards from a start vertex. At every step it adds the cheapest edge that connects a vertex in the tree to a vertex outside it. By the cut property (tree vs. rest of the graph), that edge is always safe.
It is similar to Dijkstra's algorithm: a priority queue of candidate vertices, always taking the cheapest. The difference is what "cheap" means: Dijkstra uses the total distance from the start, Prim only the weight of the single connecting edge.
The algorithm
- Start with any vertex in the tree.
- Look at all edges from tree vertices to non-tree vertices and pick the cheapest.
- Add that edge and its outside vertex to the tree.
- Repeat until all vertices are in the tree (
V - 1edges).
We use the graph from the MST intro:
| Vertex | Edges (neighbour: weight) |
|---|---|
| A | B: 7, C: 3 |
| B | A: 7, C: 2, D: 5 |
| C | A: 3, B: 2, D: 6, E: 4 |
| D | B: 5, C: 6, E: 8, F: 1 |
| E | C: 4, D: 8, F: 9 |
| F | D: 1, E: 9 |
A simple version
This first version scans all crossing edges at each step, which makes every step easy to print:
graph = {
"A": {"B": 7, "C": 3},
"B": {"A": 7, "C": 2, "D": 5},
"C": {"A": 3, "B": 2, "D": 6, "E": 4},
"D": {"B": 5, "C": 6, "E": 8, "F": 1},
"E": {"C": 4, "D": 8, "F": 9},
"F": {"D": 1, "E": 9},
}
def prim_simple(graph, start):
in_tree = {start}
mst = []
while len(in_tree) < len(graph):
crossing = [(w, u, v) for u in sorted(in_tree)
for v, w in graph[u].items() if v not in in_tree]
w, u, v = min(crossing)
options = ", ".join(f"{a}-{b}:{c}" for c, a, b in sorted(crossing))
print(f"tree {sorted(in_tree)} candidates [{options}] -> add {u}-{v} ({w})")
in_tree.add(v)
mst.append((u, v, w))
return mst
mst = prim_simple(graph, "A")
print("MST:", mst, "total:", sum(w for _, _, w in mst))tree ['A'] candidates [A-C:3, A-B:7] -> add A-C (3)
tree ['A', 'C'] candidates [C-B:2, C-E:4, C-D:6, A-B:7] -> add C-B (2)
tree ['A', 'B', 'C'] candidates [C-E:4, B-D:5, C-D:6] -> add C-E (4)
tree ['A', 'B', 'C', 'E'] candidates [B-D:5, C-D:6, E-D:8, E-F:9] -> add B-D (5)
tree ['A', 'B', 'C', 'D', 'E'] candidates [D-F:1, E-F:9] -> add D-F (1)
MST: [('A', 'C', 3), ('C', 'B', 2), ('C', 'E', 4), ('B', 'D', 5), ('D', 'F', 1)] total: 15
Each line shows the tree so far, every edge that crosses from the tree to the rest, and the cheapest one being added. The total, 15, equals the brute-force optimum from the intro.
Efficient version with a heap
Rescanning every crossing edge costs O(E) per step. With a heap of candidate edges we push each edge once when its tree vertex is added and pop the cheapest. Entries that lead to a vertex already in the tree are skipped (they are "stale"):
import heapq
graph = {
"A": {"B": 7, "C": 3}, "B": {"A": 7, "C": 2, "D": 5},
"C": {"A": 3, "B": 2, "D": 6, "E": 4}, "D": {"B": 5, "C": 6, "E": 8, "F": 1},
"E": {"C": 4, "D": 8, "F": 9}, "F": {"D": 1, "E": 9},
}
def prim(graph, start):
in_tree = {start}
heap = [(w, start, v) for v, w in graph[start].items()]
heapq.heapify(heap)
mst, skipped = [], 0
while heap and len(in_tree) < len(graph):
w, u, v = heapq.heappop(heap)
if v in in_tree:
skipped += 1
continue
in_tree.add(v)
mst.append((u, v, w))
for x, wx in graph[v].items():
if x not in in_tree:
heapq.heappush(heap, (wx, v, x))
return mst, skipped
mst, skipped = prim(graph, "A")
print(mst)
print("total:", sum(w for *_, w in mst), "stale entries skipped:", skipped)[('A', 'C', 3), ('C', 'B', 2), ('C', 'E', 4), ('B', 'D', 5), ('D', 'F', 1)]
total: 15 stale entries skipped: 0
The start vertex doesn't matter
Prim's algorithm can start anywhere. The edges are added in a different order, but the resulting tree has the same total weight (and, since all weights here are distinct, it is exactly the same tree):
import heapq
graph = {
"A": {"B": 7, "C": 3}, "B": {"A": 7, "C": 2, "D": 5},
"C": {"A": 3, "B": 2, "D": 6, "E": 4}, "D": {"B": 5, "C": 6, "E": 8, "F": 1},
"E": {"C": 4, "D": 8, "F": 9}, "F": {"D": 1, "E": 9},
}
def prim(graph, start):
in_tree, mst = {start}, []
heap = [(w, start, v) for v, w in graph[start].items()]
heapq.heapify(heap)
while heap and len(in_tree) < len(graph):
w, u, v = heapq.heappop(heap)
if v in in_tree:
continue
in_tree.add(v)
mst.append((u, v, w))
for x, wx in graph[v].items():
if x not in in_tree:
heapq.heappush(heap, (wx, v, x))
return mst
for start in "AF":
mst = prim(graph, start)
edges = sorted(tuple(sorted((u, v))) for u, v, _ in mst)
print(f"from {start}: order {[u + v for u, v, _ in mst]}, total {sum(w for *_, w in mst)}, edges {edges}")from A: order ['AC', 'CB', 'CE', 'BD', 'DF'], total 15, edges [('A', 'C'), ('B', 'C'), ('B', 'D'), ('C', 'E'), ('D', 'F')]
from F: order ['FD', 'DB', 'BC', 'CA', 'CE'], total 15, edges [('A', 'C'), ('B', 'C'), ('B', 'D'), ('C', 'E'), ('D', 'F')]
Disconnected graphs
If the graph is not connected, there is no spanning tree. Prim's algorithm then stops with fewer than V - 1 edges, which is easy to check. (Running it once from each unreached vertex gives a minimum spanning forest.)
Complexity
| Implementation | Time | Best for |
|---|---|---|
| Adjacency matrix + array scan | O(V²) |
dense graphs |
| Adjacency list + binary heap | O(E log V) |
sparse graphs |
Common mistake: using the distance from the start (as in Dijkstra) instead of the single edge weight. Prim compares edge weights only: a vertex far from the start can still be attached by a cheap edge.
Test yourself
Which edge does Prim's algorithm add at each step?
- The cheapest edge in the whole graph
- The cheapest edge from a tree vertex to a non-tree vertex
- The edge closest to the start vertex
- Any edge that doesn't form a cycle
Starting Prim's algorithm on the lesson's graph from A, which edge is added first?
- D-F (1)
- B-C (2)
- A-C (3)
- A-B (7)
How does Prim's algorithm differ from Dijkstra's?
- Prim uses a stack
- Prim prioritises by single edge weight, Dijkstra by total distance from the start
- Dijkstra only works on trees
- There is no difference