function prim(graph: Graph, start: Node) {const inTree = new Set([start]);
const tree: Edge[] = [];
while (inTree.size < graph.nodes.length) {let lightest: Edge | null = null;
for (const edge of graph.edges) {if (inTree.has(edge.from) === inTree.has(edge.to)) continue;
if (!lightest || edge.weight < lightest.weight) lightest = edge;
}
tree.push(lightest!);
inTree.add(inTree.has(lightest!.from) ? lightest!.to : lightest!.from);
}
return tree;
}
Start: the tree is just A. Total weight 0.
Understanding Prim
The idea
Prim's algorithm builds a minimum spanning tree by growing it from one node. At each step it looks at every edge with exactly one endpoint in the tree, the crossing edges, and adds the lightest one together with its outside endpoint. After V − 1 additions every node is in the tree.
It is correct because of the cut property: the lightest edge crossing any cut belongs to some minimum spanning tree. The version shown scans all edges each round; the real one keeps the crossing edges in a heap, exactly like Dijkstra with the edge weight in place of the path length.
The four stages
Complexity
Versus its siblings
Pseudocode
PRIM(graph, source)
tree ← {source}while tree does not span graph
edge ← the lightest edge with one endpoint in tree
add edge and its other endpoint to tree
When to use
Pitfalls
History
Vojtěch Jarník published the algorithm in 1930 to lay out electricity lines in Moravia. Robert Prim rediscovered it at Bell Labs in 1957, and Edsger Dijkstra again in 1959 in the same paper as his shortest-path algorithm, which is why it is sometimes called the Prim–Jarník or DJP algorithm.