Prim's algorithm
Advanced · 11 min · code in PHP, JavaScript, Java and Go
Where you will meet this in real life
Prim's algorithm builds the cheapest set of links that connects every place, growing from one start point and always adding the cheapest link that reaches a new place. The result has no loops and no wasted links.
Practical use cases
- Web app: Planning fibre or cable for new offices. A telecom dashboard has 25 offices and a price for laying cable between each pair. Prim grows the network from the head office, always adding the cheapest link to an office not yet connected, and ends with a plan that connects everyone for the lowest total cost.
- Web app: Delivery hub connections. A logistics app needs trucks to link all depots without paying for extra roads. The tool shows the cheapest backbone as lines on a map, and the cost summary is just the sum of the chosen links.
- Web app: Random maze generator. A game page creates a different maze each time. Starting from one cell and repeatedly joining a random unvisited neighbour with the Prim approach gives a perfect maze with no loops and a path to every cell. Because every run starts from a random choice, players get a new maze each time they reload the page, with no hand-drawn levels.
- System: Pipes, grids and data clusters. Water pipes, power lines and data clustering all want everything connected as cheaply as possible, which this algorithm provides. In each of these, the network grows outward like a spreading puddle, taking the cheapest next link and never creating a wasteful loop.
The story: The Water Pipes of Rangoli Colony
A new colony called Rangoli had six houses and no water pipes. The municipality had a list of possible pipe routes, each with a price. They could afford to connect everything, but they wanted the cheapest network that reached every house. Not a single pipe more than needed.
The engineer, Mrs. Sharma's sister, had a calm method. "Start with one house. It has water. Now look at all pipes that connect a watered house to a dry house. Pick the cheapest one. Lay it. Another house now has water." Repeat.
She never laid a pipe between two houses that already had water, because that would be a waste. She only grew the watered blob by one house at a time, always by the cheapest possible bridge. After five pipes, all six houses were connected, and no other plan could have been cheaper.
That grow-from-one-spot, cheapest-edge-first method is Prim's algorithm for the minimum spanning tree: the cheapest set of edges that connects every vertex without forming a loop.
How to spot this problem, and where you need it
You must connect every point into one network using the cheapest total set of links, with no need for backups or loops.
Signs you need it
- The wording says "connect all", "minimum total cost" and "no cycles" or "minimum spanning tree".
- Adding extra links only adds cost, since one route between any two points is enough.
- The network is dense, with many possible links between points, and you can grow outward from one starting place.
Where to use it in a project
- Cost planning screens for cabling, roads or pipelines between sites.
- Clustering or grouping features where points are joined cheapest-first, and procedural maze or map generation in games.
The solution
Pick any start and mark it as part of the network. Put its links in a priority queue (cheapest comes out first). Repeatedly take the cheapest link; if it reaches a place not yet in the network, add the link and that place, then add the new place's links to the queue. If it reaches a place already inside, skip it. Stop when all places are in. Each step is locally cheapest, and this is proven to give the cheapest whole.
Payoff: Before: connecting 25 offices by guesswork, costing 40 percent extra. After: a provably cheapest plan using exactly 24 links.
Explain it like I am 8
Imagine a puddle of water spreading across a floor. Each step, it creeps along the cheapest path to a new dry spot. It never goes back to a spot that is already wet. When the whole floor is wet, you have used the cheapest set of paths.
How it works, step by step
- Pick any start vertex and mark it as part of the tree.
- Look at all edges that connect a tree vertex to a vertex outside the tree.
- Take the cheapest one. Add the edge and its new vertex to the tree.
- Repeat until all vertices are in the tree (V − 1 edges).
- Use a min-heap of candidate edges so that picking the cheapest is quick.
The code in four languages
PHP
<?php
// graph: node => [neighbour => cost]. Returns [edges chosen, total cost].
function prim(array $graph, string $start): array {
$inTree = [$start => true];
$pq = new SplPriorityQueue();
$pq->setExtractFlags(SplPriorityQueue::EXTR_BOTH);
foreach ($graph[$start] as $v => $w) $pq->insert([$start, $v, $w], -$w); // min-heap via -cost
$edges = [];
$total = 0;
while (!$pq->isEmpty() && count($inTree) < count($graph)) {
$top = $pq->extract();
[$u, $v, $w] = $top['data'];
if (isset($inTree[$v])) continue; // both ends already connected: skip
$inTree[$v] = true; // v joins the blob
$edges[] = "$u-$v ($w)";
$total += $w;
foreach ($graph[$v] as $x => $c) {
if (!isset($inTree[$x])) $pq->insert([$v, $x, $c], -$c);
}
}
return [$edges, $total];
}
$graph = [
'A' => ['B' => 4, 'C' => 3],
'B' => ['A' => 4, 'C' => 1, 'D' => 2],
'C' => ['A' => 3, 'B' => 1, 'D' => 4, 'E' => 6],
'D' => ['B' => 2, 'C' => 4, 'E' => 2, 'F' => 5],
'E' => ['C' => 6, 'D' => 2, 'F' => 3],
'F' => ['D' => 5, 'E' => 3],
];
[$edges, $total] = prim($graph, 'A');
echo implode(', ', $edges) . "\nTotal: $total";JavaScript
// graph: node -> { neighbour: cost }. Returns { edges, total }.
function prim(graph, start) {
const inTree = new Set([start]);
const edges = [];
let total = 0;
// Candidate pipes leaving the blob: [cost, from, to]. (A real heap would be faster than sorting.)
let cand = Object.entries(graph[start]).map(([v, w]) => [w, start, v]);
while (cand.length && inTree.size < Object.keys(graph).length) {
cand.sort((a, b) => a[0] - b[0]); // cheapest first
const [w, u, v] = cand.shift();
if (inTree.has(v)) continue; // both ends already connected: skip
inTree.add(v); // v joins the blob
edges.push(u + '-' + v + ' (' + w + ')');
total += w;
for (const [x, c] of Object.entries(graph[v])) {
if (!inTree.has(x)) cand.push([c, v, x]);
}
}
return { edges, total };
}
const graph = {
A: { B: 4, C: 3 },
B: { A: 4, C: 1, D: 2 },
C: { A: 3, B: 1, D: 4, E: 6 },
D: { B: 2, C: 4, E: 2, F: 5 },
E: { C: 6, D: 2, F: 3 },
F: { D: 5, E: 3 },
};
const { edges, total } = prim(graph, 'A');
console.log(edges.join(', ') + '\nTotal: ' + total);Java
import java.util.*;
public class Main {
// A pipe leaving the blob: from u to v at a cost.
record Pipe(int cost, String from, String to) {}
// graph: node -> {neighbour: cost}. Returns the chosen edges; the total is printed by the caller.
static List<Pipe> prim(Map<String, Map<String, Integer>> graph, String start) {
Set<String> inTree = new HashSet<>(List.of(start));
List<Pipe> chosen = new ArrayList<>();
// The queue always hands back the cheapest pipe first.
PriorityQueue<Pipe> pq = new PriorityQueue<>(Comparator.comparingInt(Pipe::cost));
for (var e : graph.get(start).entrySet()) pq.add(new Pipe(e.getValue(), start, e.getKey()));
while (!pq.isEmpty() && inTree.size() < graph.size()) {
Pipe p = pq.remove();
if (inTree.contains(p.to())) continue; // both ends already connected: skip
inTree.add(p.to()); // v joins the blob
chosen.add(p);
for (var e : graph.get(p.to()).entrySet()) {
if (!inTree.contains(e.getKey())) pq.add(new Pipe(e.getValue(), p.to(), e.getKey()));
}
}
return chosen;
}
public static void main(String[] args) {
Map<String, Map<String, Integer>> graph = Map.of(
"A", Map.of("B", 4, "C", 3),
"B", Map.of("A", 4, "C", 1, "D", 2),
"C", Map.of("A", 3, "B", 1, "D", 4, "E", 6),
"D", Map.of("B", 2, "C", 4, "E", 2, "F", 5),
"E", Map.of("C", 6, "D", 2, "F", 3),
"F", Map.of("D", 5, "E", 3));
List<String> edges = new ArrayList<>();
int total = 0;
for (Pipe p : prim(graph, "A")) {
edges.add(p.from() + "-" + p.to() + " (" + p.cost() + ")");
total += p.cost();
}
System.out.println(String.join(", ", edges) + "\nTotal: " + total);
}
}Go
package main
import (
"fmt"
"sort"
"strings"
)
// A pipe leaving the blob: from u to v at a cost.
type pipe struct {
cost int
from, to string
}
// prim: graph is node -> {neighbour: cost}. Returns the chosen pipes and the total cost.
func prim(graph map[string]map[string]int, start string) ([]pipe, int) {
inTree := map[string]bool{start: true}
var chosen []pipe
total := 0
// Candidate pipes leaving the blob. (A real heap would be faster than sorting.)
var cand []pipe
for v, w := range graph[start] {
cand = append(cand, pipe{w, start, v})
}
for len(cand) > 0 && len(inTree) < len(graph) {
sort.Slice(cand, func(i, j int) bool { return cand[i].cost < cand[j].cost }) // cheapest first
p := cand[0]
cand = cand[1:]
if inTree[p.to] {
continue // both ends already connected: skip
}
inTree[p.to] = true // v joins the blob
chosen = append(chosen, p)
total += p.cost
for x, c := range graph[p.to] {
if !inTree[x] {
cand = append(cand, pipe{c, p.to, x})
}
}
}
return chosen, total
}
func main() {
graph := map[string]map[string]int{
"A": {"B": 4, "C": 3},
"B": {"A": 4, "C": 1, "D": 2},
"C": {"A": 3, "B": 1, "D": 4, "E": 6},
"D": {"B": 2, "C": 4, "E": 2, "F": 5},
"E": {"C": 6, "D": 2, "F": 3},
"F": {"D": 5, "E": 3},
}
chosen, total := prim(graph, "A")
var edges []string
for _, p := range chosen {
edges = append(edges, fmt.Sprintf("%s-%s (%d)", p.from, p.to, p.cost))
}
fmt.Println(strings.Join(edges, ", ") + "\nTotal: " + fmt.Sprint(total))
}Time: O(E log V) · Extra space: O(V + E). With a min-heap, each edge is pushed and popped at most once. Great for dense graphs too.
Watch out for
- Adding an edge whose both ends are already in the tree. That creates a cycle and wastes cost.
- Using Prim on a disconnected graph and expecting one tree. You would get a tree for one component only.
- Mixing up Prim with Dijkstra. Prim compares the edge weight alone; Dijkstra compares the total path cost from the start.
Quick check
- At each step Prim picks…
- The cheapest edge anywhere in the graph
- The edge to the nearest vertex by hops
- The cheapest edge leaving the current tree
- How many edges does a minimum spanning tree of V vertices have?
- V − 1
- V
- V + 1
- What is the key difference between Prim and Dijkstra?
- Prim handles negative edges
- Prim compares single edge weights, Dijkstra compares total distances
- There is no difference