AlgoViz

Prim's algorithm

medium 22 min

A minimum spanning tree connects every vertex of a weighted, undirected graph with the least total edge weight.

Where it shows up

The same pattern appears across everyday software.

  • Laying cable, pipes and power lines

    Connecting buildings, substations or homes with the least total cable or pipe is the MST problem almost word for word. Prim's 1957 paper came out of exactly this kind of work on telephone and power networks at Bell Labs.

  • Computer network design

    The original app's network example: a server and machines where each possible link has a cost. An MST gives the cheapest layout that keeps everything reachable. Ethernet's Spanning Tree Protocol also prunes redundant links down to a tree, though it picks by port cost from a root bridge rather than running Prim directly.

  • Clustering

    Build an MST over data points with distance as the weight, then delete the k - 1 heaviest edges: what remains is k clusters. This is single-linkage clustering, and on dense all-pairs data the O(V²) array Prim is the natural way to build the tree.

  • Approximating the travelling salesman

    For distances that obey the triangle inequality, walking an MST in depth-first order and skipping repeated cities gives a tour at most twice the optimum. Christofides' algorithm starts from the same MST.

  • Maze generation

    Treat the cells of a grid as vertices and the walls between them as edges with random weights. Running randomised Prim knocks down walls to form a spanning tree, giving a perfect maze: every cell reachable, exactly one path between any two.