Algorithms · Visualized
Prim's MST
Graph Algorithms
Traverse, order, and find shortest paths and spanning trees on graphs — the machinery behind maps, networks, schedulers and dependency resolvers.
A minimum spanning tree connects all V nodes using V−1 edges of minimum total weight. Time: O(E log V) average, O(E log V) worst; space: O(V + E) for the adjacency list and priority queue.
Big-O: Traversals O(V + E); Dijkstra O(E log V) with a heap; Bellman–Ford O(V·E); Floyd–Warshall O(V³); MST O(E log E).
Prim's Minimum Spanning Tree
Graph AlgorithmsA minimum spanning tree connects all V nodes using V−1 edges of minimum total weight. Prim grows one tree from an arbitrary start: at every step it takes the cheapest edge with exactly one endpoint inside the tree, pulling a new node in. Cut optimality guarantees this greedy choice is always safe.
How Prim's MST Works
- Start with any node in the tree; every other node is outside.
- Look at all edges that cross from inside the tree to outside.
- Pick the crossing edge of minimum weight and add it — together with the new endpoint — to the tree.
- Repeat until all V nodes are inside; exactly V−1 edges will have been chosen.
- A priority queue of frontier edges makes each pick O(log E).
Prim's MST Worked Example
Input: {graph: A—B(4), A—C(2), B—C(1), B—D(5), C—D(8), C—E(10), D—E(2), D—F(6), E—F(3), start: A}
From {A}: cheapest crossing edge A—C(2). From {A,C}: B—C(1) beats A—B(4). From {A,C,B}: B—D(5). From {A,C,B,D}: D—E(2). From {A,C,B,D,E}: E—F(3). Total = 2+1+5+2+3 = 13 — the minimum possible.
import heapq
def prim_mst(n, edges):
adj = [[] for _ in range(n)]
for u, v, w in edges:
adj[u].append((w, v))
adj[v].append((w, u))
visited = [False] * n
total = 0
pq = [(0, 0)] # (weight, node)
while pq:
w, u = heapq.heappop(pq)
if visited[u]:
continue
visited[u] = True # cheapest crossing edge wins
total += w
for wv, v in adj[u]:
if not visited[v]:
heapq.heappush(pq, (wv, v))
return totalBehind the Scenes Execution
Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.
Prim's MST Time & Space Complexity
When to Use Prim's MST
- Network cabling: connect offices, power lines or clusters with the least total wire.
- Approximation building blocks (e.g. the 2-approximation for metric TSP) and cluster analysis.
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Keep the momentum going
Step through a related structure, pattern or course — the ideas reinforce each other and stick faster.