Skip to content
StackDecode
GraphsAnimated

Prim's Algorithm

Grow a spanning tree by always adding the cheapest edge leaving it.

Time

O(E log V)

Extra space

O(V)

Use it for

Minimum spanning tree on dense graphs.

How it works

  1. Start from any node; the tree so far is just that node.
  2. Look at every edge leaving the tree and pick the cheapest one that reaches a new node.
  3. Add that edge and node to the tree.
  4. Repeat until all nodes are in. The edges picked form a minimum spanning tree.

Watch it run

Loading animation…