Abstract flowing gradient in deep indigo and blue tones, smooth and luminous, evoking a modern digital learning atmosphere

Computer Science and programming articles. We do not sell courses.

Prim’s algorithm for minimum spanning trees

A minimum spanning tree (MST) is the smallest-cost way to connect every vertex in a connected, undirected, weighted graph without creating a cycle. The result contains exactly (V-1) edges, where (V) is the number of vertices, and minimises the sum of edge weights. This makes MSTs useful for designing road, rail, fibre, water and power networks, where each possible connection has a different cost.

Prim’s algorithm solves this problem greedily. It grows one tree from any starting vertex, repeatedly selecting the cheapest edge that joins the current tree to a vertex outside it. The explanation develops that idea through graph construction, a correctness argument, pseudocode, a Python implementation and complexity analysis, with Australian network examples along the way.

Why minimum spanning trees matter

In many engineering problems, connecting every site matters more than choosing a direct route between every pair. A retailer such as Woolworths or Coles may model distribution depots, stores and freight links as a weighted graph, then seek a low-cost backbone that keeps every location reachable. The same abstraction can help compare Melbourne’s tram links or plan remote mine communications and fibre routes in the Australian telecommunications market around Perth and Brisbane.

The MST is not the shortest-path tree for one destination, and it does not preserve every inexpensive link. It finds a globally economical set of connections that spans the network. A useful mental image is a tree with branches: removing any selected edge would disconnect it. Three classic methods share this goal but make different implementation trade-offs.

Algorithm Main strategy Common strength Typical time
Prim Grow one tree using the cheapest edge across the current cut Simple concept; effective for many graph shapes (O(E \log V)) with a binary heap
Kruskal Sort edges and add those that join different components Natural for sparse graphs (O(E \log E))
Borůvka Add the cheapest outgoing edge for each component Handles very large graphs cleanly (O(E \log V))

Turning Australian routes into a weighted graph

Represent each place as a vertex and each usable connection as an undirected edge. The weight can represent kilometres, travel minutes, construction cost, energy use or Australian-dollar expenditure. A graph need not use straight-line distance: Australia’s sparse settlement pattern means the Perth–Adelaide road corridor, for example, is roughly 2,700 kilometres, while the built route bends around geography. Distances and journey times should therefore be chosen deliberately for the decision being made.

Here is a small illustrative network:

graph = {
    "Sydney": {"Melbourne": 880, "Brisbane": 900},
    "Melbourne": {"Sydney": 880, "Adelaide": 735, "Brisbane": 1420},
    "Brisbane": {"Sydney": 900, "Melbourne": 1420},
    "Adelaide": {"Melbourne": 735, "Perth": 2700},
    "Perth": {"Adelaide": 2700}
}

These figures are corridor lengths, not current route advice. Australia drives on the left, and urban congestion around Sydney and Melbourne can change travel times without changing the physical connections. If the objective is rapid delivery rather than physical distance, the same graph can use peak-hour travel times as weights. A graph problem can even include ferries, freight rail and proposed fibre links as parallel choices.

The MST objective also assumes one scalar weight. If a project must balance cost against resilience, a single total may hide an undesirable design. A more advanced version can penalise certain edges, require a second disjoint route, or optimise several separate trees. Those constraints move beyond the basic spanning-tree model, but the same graph representation remains useful.

The cut property behind each greedy choice

At any stage, let (S) be the vertices already in Prim’s tree and let (V-S) be the remaining vertices. The edges with one endpoint in each set form a cut. The cut property states that a minimum-weight edge crossing any cut is safe: it can be included in some MST of the original graph. Prim chooses exactly such an edge, which is why its local greedy decision preserves the possibility of an optimal result.

To see why, suppose (e) is the cheapest edge across a cut and an MST (T) does not contain it. Adding (e) to (T) creates one cycle. That cycle must contain another edge (f) crossing the same cut. Since (e) is no heavier than (f), replacing (f) with (e) produces a spanning tree whose weight is no greater than (T)’s. Thus an MST containing (e) exists.

The wording “some MST” matters. If several edges share the minimum weight, different runs or tie-breaking rules can produce different minimum spanning trees with the same total cost. The algorithm does not need to find every possible MST; it only needs one. Prim is therefore a greedy algorithm, but it is greedy with a proven safety condition rather than an arbitrary local preference.

This differs from Dijkstra’s shortest-path algorithm. A Prim heap is keyed by an edge’s weight, whereas a Dijkstra heap is keyed by the total distance from the source. A heavier individual edge may still be correct in Prim if it is the cheapest available connection to the growing tree, even when another route would give a shorter path from the starting city.

A step-by-step Prim algorithm walkthrough

The implementation pattern has four actions: choose any start vertex, place its incident edges in a min-priority queue, extract the cheapest edge whose other endpoint is not yet selected, and add that vertex plus the edge to the tree. After adding a vertex, insert its edges to unvisited vertices. Repeat until every vertex has joined.

PRIM(G, start):
    T = empty tree
    S = {start}
    Q = min-priority queue of edges leaving S

    while Q is not empty:
        e = extract_min(Q)
        if e connects S to a vertex outside S:
            add e to T
            add the outside endpoint to S
            insert its edges to vertices outside S into Q
    return T

For the Australian example, start at Perth. Its only edge reaches Adelaide at 2,700 kilometres, so that connection enters the tree. Adelaide then offers Melbourne at 735 kilometres and Sydney at 1,490 kilometres; Melbourne is selected. From the growing tree, the 880-kilometre Melbourne–Sydney edge beats the 1,420-kilometre Melbourne–Brisbane edge, so Sydney joins. Brisbane finally connects through the 900-kilometre Sydney–Brisbane link.

The selected edge weights are 2,700, 735, 880 and 900 kilometres, for a total of 5,215 kilometres across five cities. The sequence can vary when equal weights exist, but a connected graph with distinct weights has a unique MST. Notice that Prim does not build shortest paths between all pairs: it only maintains one connected, cycle-free structure, and each added edge is the cheapest edge currently crossing a cut.

A practical Python implementation

A Python adjacency list maps each vertex to its neighbours and edge weights. The heapq module provides the min-heap needed for efficient extraction. If you need a broader refresher before implementing the graph, the Python programming guide explains the relevant data structures and language features.

import heapq

def prim(graph, start):
    if not graph:
        return [], 0

    visited = {start}
    frontier = [
        (weight, start, neighbour)
        for neighbour, weight in graph[start].items()
    ]
    heapq.heapify(frontier)
    tree = []
    total = 0

    while frontier:
        weight, source, target = heapq.heappop(frontier)
        if target in visited:
            continue

        visited.add(target)
        tree.append((source, target, weight))
        total += weight

        for neighbour, edge_weight in graph[target].items():
            if neighbour not in visited:
                heapq.heappush(
                    frontier, (edge_weight, target, neighbour)
                )

    if len(visited) != len(graph):
        raise ValueError("The graph is disconnected")

    return tree, total

The tuple order matters when two edges have equal weight: heap elements are compared field by field, so storing the weight first ensures the tie is resolved by vertex names rather than by comparing incompatible values. Pushing every candidate edge creates a lazy deletion queue. An extracted edge is ignored when its target has already joined the tree, and the best remaining edge is always at the top.

For a connected graph, this version runs in (O((V+E)\log V)) time with a binary heap and uses (O(V+E)) space. For a disconnected graph, no single spanning tree exists; the function raises an error rather than silently returning a forest. To find a minimum spanning forest, run the same growth process from every unvisited vertex and combine the resulting components.

Performance limits and working recommendations

Prim’s running time depends on the graph representation and priority queue. With an adjacency list and binary heap, the usual bound is (O((V+E)\log V)); with an adjacency matrix, scanning for the next minimum can take (O(V^2)), which can be preferable for small, dense graphs. The edge count matters as much as the vertex count. Very large networks may also use Borůvka’s method or specialised geometric libraries rather than a general-purpose heap.

The algorithm becomes an MST when weights are additive and the graph is connected and undirected. Directed graphs require a different structure, such as an arborescence, because each vertex may need its own incoming connection. If weights vary over time—as with peak-hour traffic or variable fibre lease costs—the MST describes only the snapshot supplied to the algorithm. MSTs also appear in feature construction and clustering; the machine learning resources show where such graph-based preprocessing fits into broader pipelines.

For reliable use, follow these working recommendations:

The core habit is simple: express the infrastructure as a weighted graph, verify that Prim’s assumptions hold, and use the cut property to justify every edge added. With those checks in place, the algorithm becomes a dependable tool for Australian transport planning, market-distribution design and connected data systems.