Loading...
Given a connected, undirected, weighted graph G, construct a spanning tree of minimum total weight. If the graph is disconnected, Prim's run from one start vertex builds an MST for that component only (can repeat to get a minimum spanning forest).
1PRIM(G=(V,E), w, start):2 for each v in V:3 key[v] = +∞4 parent[v] = NIL5 key[start] = 06 PQ = min-priority-queue keyed by key[]7 insert all vertices into PQ8 inMST = ∅9 while PQ not empty:10 u = extract-min(PQ)11 add u to inMST12 if parent[u] ≠ NIL: add edge (parent[u], u) to MST13 for each (u,v) in Adj[u]:14 if v ∉ inMST and w(u,v) < key[v]:15 key[v] = w(u,v)16 parent[v] = u17 decrease-key(PQ, v)18 return MST
Decrease-key operations dominate with heaps. For dense graphs (m ≈ n^2) the simple O(n^2) implementation is practical and often faster in practice.