Maths WorkshopMaths problems with full solutions
Exercise 1695Combinatorics › Graph theoryL1Added 3 Nov 2026

Prim's algorithm

#Prim#MST#greedy

Statement

Describe Prim's algorithm for finding an MST.

Hint

Grow a tree from a starting vertex, always adding the cheapest edge connecting the tree to a new vertex.

Show solutionHide solution

Solution

Algorithm.
1. Start at any vertex rr. Set T={r}T=\{r\}, priority queue of edges incident to TT with weights.
2. Repeatedly: pick the minimum-weight edge from TT to V∖TV\setminus T, add its other endpoint to TT and the edge to the MST.
3. Stop when T=VT=V.

Complexity. O(∣E∣log⁡∣V∣)O(|E|\log|V|) with a binary heap.

Conclusion. Prim computes an MST.