← Knowledgebase

Prim's algorithm: growing a minimum spanning tree

The same problem, another greedy rule

A minimum spanning tree connects every node of a weighted graph using the edges of smallest total weight. Kruskal's algorithm takes the lightest edges anywhere in the graph, so its pieces grow separately and merge. Prim's algorithm keeps one tree from the start and grows it outwards:

  1. Start the tree at any node.
  2. Repeatedly add the lightest edge leaving the tree: one end inside, one outside. The outside node joins.
  3. Stop when every node has joined.

It's safe for the same reason as Kruskal: some edge has to connect the tree to the rest of the graph, and the lightest such edge can always be part of a minimum spanning tree.

Keys and the priority queue

Scanning every edge leaving the tree at each step would be slow. Instead, every node outside the tree has a key: the weight of the lightest edge known to connect it to the tree (∞ if none). When a node joins, check its edges: if edge u–v is lighter than v's key, v's key drops to that weight. The next node to join is the one with the smallest key, which is a job for a min-priority queue.

If that sounds like Dijkstra's algorithm, it is: the structure is identical. The one difference is the update rule:

DijkstraPrim
A node's number isthe length of the best path from the startthe weight of the best single edge to the tree
Checking edge u–v (weight w)new distance = min(dist(v), dist(u) + w)new key = min(key(v), w)
Resulta shortest-path treea minimum spanning tree

Reading the pictures

A key ∞ B has a key: waiting in the queue C just joined D in the tree

Numbers under the nodes are their keys. Solid blue edges are in the tree; dashed blue edges are the edges behind the current keys. Ties are broken alphabetically, and a key only changes when an edge is strictly lighter, so each question has one right answer.

Prim
TimeO((V + E) log V) with a binary heap
Prim or Kruskal?Both give a minimum tree. Prim suits dense graphs and adjacency lists; Kruskal suits sparse graphs given as a list of edges.