Prim's MST visualization

Grow one tree by always adding the cheapest edge leaving it.

Start from any vertex. Among all edges that connect the tree to a vertex outside it, pick the lightest — the cut property guarantees it belongs to some minimum spanning tree.

Edge case: on a disconnected graph no spanning tree exists; Prim only spans the start vertex's component.

Complexity

Time: best O(E log V), average O(E log V), worst O(E log V). Space: O(V + E). Difficulty: Intermediate.

Pseudocode

procedure prim(G, s):
  inTree ← {s}; pq ← edges leaving s
  while pq not empty:
    (w, u, v) ← pq.popMin()
    if v in inTree: continue          // would form a cycle
    add edge (u, v) to MST; inTree.add(v)
    push edges from v to vertices outside the tree
  if |inTree| < |V|: graph is disconnected

More graphs algorithms