MST — Prim's Algorithm
Build a minimum spanning tree by growing one tree outward from a start vertex.
Open on GeeksforGeeks ↗Intuition
Keep one connected tree and repeatedly absorb whichever outside vertex is cheapest to attach. Each vertex remembers key[v] — the cost of the cheapest single edge joining it to the current tree. The cut property guarantees this is safe: the lightest edge crossing the boundary between tree and non-tree always belongs to some MST.
Approach
Track the cheapest way in
key[v] starts ∞ (0 for the seed). Repeatedly pick the unabsorbed vertex with the smallest key, add that cost to the total, and mark it in-tree.
Update the frontier
After absorbing u, each neighbour v outside the tree may now have a cheaper entry: key[v] = min(key[v], w(u, v)). Only edges crossing the cut matter.
Why greedy is optimal
The cut property: for any split of the vertices, the lightest crossing edge is in some MST. Every step takes exactly such an edge, so the final tree is minimal.
Solution & live demo
Edge cases
No MST exists; the loop stops early with fewer than V−1 edges.
Ties can be broken arbitrarily — multiple MSTs of identical total weight.
Prim's with a heap is usually preferred over Kruskal's when E ≈ V².