Lesson 28 · Problem-solving methods

Prim's Algorithm

Start anywhere and repeatedly absorb the nearest vertex. One tree grows outward, and a priority queue keeps the cheapest crossing edge at hand.

Prim's Algorithm concept diagramPrim's algorithm part way through, started at A. The tree A, B, C, E sits inside a dashed boundary, joined by edges A-B 4, B-C 2 and C-E 3. Four frontier edges cross the boundary; the cheapest, E-F 1, is next. A priority queue on the right lists the frontier: E-F 1 on top, then B-D 5, D-E 7, a stale A-C 8, and C-D 9.tree, grown from A864235971 · minABCEDFstart#1#2#3outsidenextpriority queueE-F1B-D5D-E7A-C8C-D9top = cheapest edge leaving the treeA-C stale: C is already inside
1

One Tree, Growing Outward

  1. Start at any vertex; mark it as in the tree.
  2. Collect every edge leaving the tree into a priority queue.
  3. Extract the cheapest edge whose far endpoint is still outside.
  4. Absorb that vertex and add its edges to the queue.
  5. Stop when all V vertices are in the tree.

Prim's algorithm builds a minimum spanning tree by growing a single tree outward. Start at any vertex, then repeatedly add the cheapest edge connecting a vertex inside the tree to one outside it.

The starting vertex does not matter. Every choice yields an MST of the same total weight — and the same tree, unless weights are tied.

The contrast with Kruskal is structural. Prim's intermediate state is always one connected tree; Kruskal's is a scattered forest. That difference is what makes the data structures different: Prim never needs a cycle test, because any edge to a vertex already in the tree is rejected by definition.

  • Disconnected graph: the tree covers only the start vertex's component; restart from an unvisited vertex to build a spanning forest
  • Negative weights are fine, because only comparisons between weights matter
  • Tied weights: the total is fixed, but which edges are chosen can change
2

The Priority Queue and the Frontier

The recurring question is: of all edges leaving the tree right now, which is cheapest?

Scanning every edge each round answers it in O(E) per step and O(V·E) overall — correct and far too slow.

A priority queue answers it in O(log V). The standard formulation keeps a key[v] for each vertex — the cheapest known edge reaching it from the tree — with all keys starting at infinity except the start vertex at zero.

Each time a vertex is absorbed, its neighbours' keys are examined and lowered if the new edge is cheaper. That is the decrease-key operation, and it happens at most once per edge, which is where the E log V comes from.

Most library heaps (Python's heapq, C++'s priority_queue, Java's PriorityQueue) have no decrease-key. Code written with them uses lazy Prim's algorithm instead: push a new entry whenever a cheaper edge appears, and when an entry pops whose vertex is already in the tree, discard it as stale. The heap can then hold up to E entries, so the cost is O(E log E), which is the same class as O(E log V). The code and the demo on this page use this version.

  • Eager version: one heap entry per vertex, lowered by decrease-key
  • Lazy version: one entry per edge, stale ones skipped on pop
  • Both give O(E log V) with a binary heap; Fibonacci heap O(E + V log V)
3

Prim vs Kruskal

Both are greedy, both are justified by the cut property, and both produce a minimum spanning tree. The difference is which cut they consider.

Prim always takes the cut separating its tree from everything else. Kruskal takes whichever cut the next cheapest edge happens to cross. Same guarantee, different order of discovery.

With a binary heap Prim is O(E log V) and Kruskal is O(E log E). Since log E is at most 2 log V, these are the same class — the choice is decided by graph shape and input format, not asymptotics.

On a dense graph Prim wins: the adjacency-matrix variant runs in O(V²) with no heap at all, which beats sorting V² edges. On a sparse graph Kruskal wins, since few edges make sorting cheap. And if the graph arrives as an unsorted edge list, Kruskal needs no conversion.

Two greedy algorithms, one guarantee
PrimKruskal
GrowsOne connected treeA forest that merges
PicksCheapest edge leaving the treeCheapest edge anywhere
NeedsAdjacency list or matrixA sorted edge list
Cycle testNone — membership sufficesUnion-find
With a heapO(E log V)O(E log E)
Best onDense graphsSparse graphs
No-heap formO(V²) with a matrixstill needs the sort
  • Prim's intermediate state is always connected; Kruskal's usually is not
  • Prim needs adjacency access; Kruskal needs every edge up front
  • Same tree weight either way
Implementation

Code in Python, C++ and Java

import heapq

ADJACENCY = {
    "A": [("B", 4), ("C", 8)],
    "B": [("A", 4), ("C", 2), ("D", 5)],
    "C": [("A", 8), ("B", 2), ("D", 9), ("E", 3)],
    "D": [("B", 5), ("C", 9), ("E", 7), ("F", 6)],
    "E": [("C", 3), ("D", 7), ("F", 1)],
    "F": [("D", 6), ("E", 1)],
}


def prim(adjacency, start):
    in_tree = {start}
    frontier = [(w, start, v) for v, w in adjacency[start]]
    heapq.heapify(frontier)
    tree, total = [], 0

    while frontier and len(in_tree) < len(adjacency):
        weight, u, v = heapq.heappop(frontier)

        if v in in_tree:
            print(f"  drop   {u}-{v} ({weight})   {v} already absorbed")
            continue

        in_tree.add(v)
        tree.append((u, v, weight))
        total += weight
        print(f"  absorb {u}-{v} ({weight})   tree now {' '.join(sorted(in_tree))}")

        for nxt, w in adjacency[v]:
            if nxt not in in_tree:
                heapq.heappush(frontier, (w, v, nxt))

    return tree, total


def main():
    tree, total = prim(ADJACENCY, "A")
    print("\nMST edges ", " ".join(f"{u}-{v}" for u, v, _ in tree))
    print(f"total      {total}")


if __name__ == "__main__":
    main()
#include <iostream>
#include <map>
#include <queue>
#include <set>
#include <string>
#include <tuple>
#include <vector>
using Entry = std::tuple<int, std::string, std::string>; // weight, from, to
int main() {
    const std::map<std::string, std::vector<std::pair<std::string, int>>> adjacency = {
    {
        "A", {{"B", 4}, {"C", 8}}
    },
    {
        "B", {{"A", 4}, {"C", 2}, {"D", 5}}
    },
    {
        "C", {{"A", 8}, {"B", 2}, {"D", 9}, {"E", 3}}
    },
    {
        "D", {{"B", 5}, {"C", 9}, {"E", 7}, {"F", 6}}
    },
    {
        "E", {{"C", 3}, {"D", 7}, {"F", 1}}
    },
    {
        "F", {{"D", 6}, {"E", 1}}
    },
    };
    std::set<std::string> inTree = {"A"};
    std::priority_queue<Entry, std::vector<Entry>, std::greater<Entry>> frontier;
    for (const auto& [v, w] : adjacency.at("A")) frontier.emplace(w, "A", v);
    std::vector<Entry> tree;
    int total = 0;
    while (!frontier.empty() && inTree.size() < adjacency.size()) {
        const auto [weight, u, v] = frontier.top();
        frontier.pop();
        if (inTree.count(v)) {
            std::cout << "  drop   " << u << "-" << v << " (" << weight
            << ")   " << v << " already absorbed\n";
            continue;
        }
        inTree.insert(v);
        tree.emplace_back(weight, u, v);
        total += weight;
        std::cout << "  absorb " << u << "-" << v << " (" << weight << ")   tree now";
        for (const auto& t : inTree) std::cout << " " << t;
        std::cout << "\n";
        for (const auto& [nxt, w] : adjacency.at(v)) {
            if (!inTree.count(nxt)) frontier.emplace(w, v, nxt);
        }
    }
    std::cout << "\nMST edges ";
    for (const auto& [w, u, v] : tree) std::cout << " " << u << "-" << v;
    std::cout << "\ntotal      " << total << "\n";
    return 0;
}
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.PriorityQueue;
import java.util.TreeSet;
public class Main {
    record Entry(int weight, String from, String to) {
    }
    public static void main(String[] args) {
        Map<String, List<Object[]>> adjacency = new HashMap<>();
        adjacency.put("A", Arrays.asList(new Object[] {"B", 4}, new Object[] {"C", 8}));
        adjacency.put("B", Arrays.asList(new Object[] {"A", 4}, new Object[] {"C", 2},
        new Object[] {"D", 5}));
        adjacency.put("C", Arrays.asList(new Object[] {"A", 8}, new Object[] {"B", 2},
        new Object[] {"D", 9}, new Object[] {"E", 3}));
        adjacency.put("D", Arrays.asList(new Object[] {"B", 5}, new Object[] {"C", 9},
        new Object[] {"E", 7}, new Object[] {"F", 6}));
        adjacency.put("E", Arrays.asList(new Object[] {"C", 3}, new Object[] {"D", 7},
        new Object[] {"F", 1}));
        adjacency.put("F", Arrays.asList(new Object[] {"D", 6}, new Object[] {"E", 1}));
        TreeSet<String> inTree = new TreeSet<>();
        inTree.add("A");
        PriorityQueue<Entry> frontier = new PriorityQueue<>((a, b) -> {
        if (a.weight() != b.weight()) return a.weight() - b.weight();
        if (!a.from().equals(b.from())) return a.from().compareTo(b.from());
        return a.to().compareTo(b.to());
        });
        for (Object[] e : adjacency.get("A")) {
            frontier.add(new Entry((Integer) e[1], "A", (String) e[0]));
        }
        List<String> tree = new ArrayList<>();
        int total = 0;
        while (!frontier.isEmpty() && inTree.size() < adjacency.size()) {
            Entry cur = frontier.poll();
            if (inTree.contains(cur.to())) {
                System.out.printf("  drop   %s-%s (%d)   %s already absorbed%n",
                cur.from(), cur.to(), cur.weight(), cur.to());
                continue;
            }
            inTree.add(cur.to());
            tree.add(cur.from() + "-" + cur.to());
            total += cur.weight();
            System.out.printf("  absorb %s-%s (%d)   tree now %s%n",
            cur.from(), cur.to(), cur.weight(), String.join(" ", inTree));
            for (Object[] e : adjacency.get(cur.to())) {
                if (!inTree.contains((String) e[0])) {
                    frontier.add(new Entry((Integer) e[1], cur.to(), (String) e[0]));
                }
            }
        }
        System.out.printf("%nMST edges  %s%ntotal      %d%n", String.join(" ", tree), total);
    }
}
Watch it run

Step through it

Running on same 6-vertex graph, starting at A, frontier in a priority queue

482593761ABCDEF
tree{A} — 1 of 6 vertices
any start vertex gives an MST of the same weight
Step 1

start anywhere — here, A

Prim grows one connected tree from an arbitrary vertex. The choice of start does not change the total weight, only the order in which vertices are absorbed.

Output
1 / 10
4

Using an Adjacency Matrix, No Heap

The priority-queue form is the one usually taught, but on a dense graph Prim's algorithm using adjacency matrix storage and a plain array is simpler and faster.

Keep two arrays: key[v], the cheapest known edge reaching v from the tree, and inTree[v]. Repeat V times: scan every vertex to find the smallest key not yet in the tree, add it, then update its neighbours' keys.

Each round costs O(V) for the linear scan and O(V) for the update, and there are V rounds — so O(V²) overall, with no priority queue and no decrease-key.

On a dense graph where E ≈ V², the heap version costs O(E log V) = O(V² log V), so the plain scan is faster by a log factor as well as simpler. The heap pays off when the graph is sparse, with E far below V², because then most rounds touch only a few edges.

Which implementation to reach for
GraphImplementationCost
Dense, E ≈ V²Adjacency matrix, linear scanO(V²)
Sparse, E ≈ VAdjacency list, binary heapO(E log V)
Very large, sparseFibonacci heapO(E + V log V)
  • key[] and inTree[] replace the whole priority queue
  • No stale entries and no decrease-key to implement
  • Fibonacci heaps win only in theory; their constants are large