AlgoFrames

Prim's algorithm

Prim’s algorithm grows a minimum spanning tree from one vertex, always adding the cheapest edge that reaches a new vertex.

Before you start: Kruskal's algorithm, Priority queues in practice: top-k, k-way merge, scheduling.

The idea

Lay cables starting from office A. Each new cable should reach one more office as cheaply as possible.

This greedy growth builds a minimum spanning tree (MST): edges that join every vertex with the lowest total weight.

Intuition

The tree holds only A; its edges A-C (1) and A-B (3) wait in the queue. A-C is cheapest, so C joins next.

Cut property: the cheapest edge crossing from the tree to the rest belongs to some MST.

A-C left the queue and C joined, bringing C-B and C-E. Now C-B (2) is the cheapest way out of the tree.

Complexity

Each edge is pushed at most twice, and each push or pop costs O(log V). The total is O(E log V).

An array scan instead of a heap costs O(V) per round and O(V²) overall. That is better when E is close to V².

After B joins, the queue holds A-B, C-E and B-D: one entry per pushed edge. Space is O(V + E).

Pitfalls

A-B went stale: B joined through C-B (2) first. Skip a stale edge when it is popped.

Adding B twice would count its weight twice and close a cycle.

On a new graph in two pieces, the queue empties early. Check that all V vertices joined.

Variations

For dense graphs, keep key[v], the cheapest edge into the tree, in an array. Each round scans it for the smallest key.

This is the same loop as Dijkstra, with an edge weight instead of a path length as the key.

Code

Pseudocode

inTree ← {seed}, total ← 0
push every edge of seed onto pq
while pq not empty and inTree has fewer than V vertices
  (w, u, v) ← pop the cheapest edge from pq
  if v is in inTree: skip it
  add v to inTree, total ← total + w
  push every edge (v, x) with x not in inTree
return total

Python

import heapq
def prim(adj, seed=0):
    n = len(adj)
    in_tree = [False] * n
    in_tree[seed] = True
    pq = [(w, seed, v) for v, w in adj[seed]]
    heapq.heapify(pq)
    total, count = 0, 1
    while pq and count < n:
        w, u, v = heapq.heappop(pq)
        if in_tree[v]:
            continue
        in_tree[v] = True
        total += w
        count += 1
        for x, wx in adj[v]:
            if not in_tree[x]:
                heapq.heappush(pq, (wx, v, x))
    return total

JavaScript

function prim(adj, seed = 0) {
  const n = adj.length;
  const inTree = new Array(n).fill(false);
  inTree[seed] = true;
  const pq = adj[seed].map(([v, w]) => [w, seed, v]);
  let total = 0, count = 1;
  while (pq.length > 0 && count < n) {
    pq.sort((a, b) => a[0] - b[0]);
    const [w, u, v] = pq.shift();
    if (inTree[v]) continue;
    inTree[v] = true;
    total += w;
    count++;
    for (const [x, wx] of adj[v]) {
      if (!inTree[x]) pq.push([wx, v, x]);
    }
  }
  return total;
}

Cost at a glance

TimeO(E log V)
SpaceO(V)
InputConnected undirected weighted graph
OutputMinimum spanning tree

Practice problems (6)

Prim order Warm-up

Run Prim from A on this graph. First click the vertex that joins the tree second. Then put the other vertices in the order they join.

Kruskal vs Prim Warm-up

A network has 2,000 sites and a cable price for almost every pair, about 2 million edges, stored as a 2,000 × 2,000 matrix. Which approach fits best?

Implement Prim Standard

Grow a minimum spanning tree from vertex 0 and return its total weight. Return -1 when some vertex cannot be reached.

buildAdjacency(graph) lists [neighbor, weight] pairs in JavaScript. In Python, build the lists from graph["edges"].

Supply water to every house Standard

Houses are numbered 1 to n. Digging a well at house i costs wells[i - 1]. A pipe [a, b, w] joins houses a and b for cost w. Every house needs water from its own well or through pipes from a house that has it. Return the minimum total cost.

Cost of the array version Standard

This Prim keeps an array of keys instead of a heap. The graph has n vertices and is given as an n × n matrix. Pick its time and extra space complexity.

MST on a dense matrix graph Challenge

m is an n × n symmetric matrix. m[u][v] is the weight of the edge u-v, or 0 when there is no edge. Return the weight of a minimum spanning tree, or -1 when the graph is not connected.

Aim for O(n²) time and O(n) extra space: do not build an edge list.

Related topics

Next on the path: Strongly connected components: Kosaraju and Tarjan