Graph algorithms

O(E log V)·O(V) space
Whole graph

Drag to pan; pinch or Ctrl+scroll to zoom, which stops at the whole graph; arrow keys pan once the picture has focus.

A to B, weight 5B to C, weight 6C to D, weight 5A to E, weight 5D to F, weight 5C to G, weight 8C to H, weight 7F to I, weight 2B to J, weight 3B to G, weight 7C to I, weight 8D to G, weight 8E to H, weight 6E to I, weight 5G to H, weight 7565558723788657A, the startABBCCDDEEFFGGHHIIJJPriority queue, cheapest edge outPriority queuecheapest edge out
  • Being taken

The graph has 10 nodes and 15 edges, and nothing has been explored yet. Prim grows one connected tree outwards from A.

The graph has 10 nodes and 15 edges, and nothing has been explored yet. Prim grows one connected tree outwards from A.
  1. 1put the starting vertex in the tree, and queue every edge leaving it
  2. 2take the cheapest edge in the queue
  3. 3both its ends are already in the tree, so discard it
  4. 4take the edge and its far end into the tree
  5. 5queue every edge leaving the vertex just added
  6. 6the queue has emptied: every vertex reachable from the start is in the tree
Edges taken
0
Discarded as inside
0
Candidates examined
0
Added to the queue
0
Largest the queue got
0

Complexity

BestO(E log V)
AverageO(E log V)
WorstO(E log V)
Extra spaceO(V)
E log V at n=10 predicts 50; this run took 0.

Prim

Prim starts from one vertex and keeps a single connected tree. At every step it takes the cheapest edge with one end inside the tree and the other outside, and adds that edge and its far end. The candidate edges live in a priority queue ordered by weight, so "cheapest edge leaving the tree" is one operation rather than a search.

Its frontier

A priority queue of the edges leaving the tree.

When it is the right choice

The same problem Kruskal solves, and the better choice when the graph is dense: Prim’s work is bounded by the edges leaving a growing tree rather than by sorting every edge in the graph. It is also the one to reach for when the tree has to stay connected as it grows — building outwards from a depot, say, rather than assembling pieces.

How it works

Worth noticing

Cost

Best
O(E log V)
Average
O(E log V)
Worst
O(E log V)
Extra space
O(V)
Runs on
a weighted undirected graph
Largest grid
11 by 7 cells
Largest graph
14 nodes, 28 edges

The limits are pedagogical rather than technical: this tool keeps a cost and a predecessor for every node in every recorded step, so the size of the graph sets the size of the trace directly, and a run has to stay short enough to sit and watch. A graph that would take more than three thousand steps on this algorithm is refused before a single step is generated, from a formula in the number of nodes and edges rather than by running it and finding out.

Graphs are generated from a seed, so the link in your address bar draws exactly the graph on your screen — no part of it is random in a way a reload could change.

Worth comparing

All graph algorithms