Minimum Spanning Trees

Week 14, Monday — Prim’s Algorithm

April 8, 2026

Announcements

Muddy City

You can pave road segments. Each segment costs its number of paving stones.

Goal: pave the __________ stones so every house can reach every other.

 

Which roads do you pave?

How many stones total?

 

(CS Unplugged activity)

Minimum Spanning Tree

8 2 4 7 2 1 3 9 5 A B C D E F

Input: connected, undirected graph \(G\) with edge weights

Output: subgraph \(G'\) such that:

  • \(G'\) spans \(G\) (contains all vertices)
  • \(G'\) is connected and acyclic (a tree)
  • \(G'\) has minimum total weight among all spanning trees

 

What is the MST of this graph?

Total weight = ____

Partition Property (Cut Property)

S = {A, C, D} 8 2 4 7 2 1 3 9 5 A B C D E F green = min crossing edge (always in MST)

Partition Property (Cut Property)

Split vertices into any two sets \(S\) and \(V \setminus S\).

The minimum-weight edge crossing the cut is always in some MST.

Prim’s Algorithm: Pseudocode

  1. Initialize structure:

    • For all v: d[v] = INF, p[v] = null
    • Let d[s] = 0
    • Initialize PQ by d[v]
  2. Repeat n times:

    • Remove minimum d[] unlabelled vertex: v
    • Label vertex v
    • For all unlabelled neighbors w of v:
      • If (wt[(v,w)] < d[w])
        • d[w] = wt[(v,w)]
        • p[w] = v

Where is the solution?

2 8 7 5 7 9 8 4 3 A B C D E F

Prim’s Algorithm: Design Choices

  1. Initialize structure:

    • For all v: d[v] = INF, p[v] = null
    • Let d[s] = 0
    • Initialize PQ by d[v]
  2. Repeat n times:

    • Remove minimum d[] unlabelled vertex: v
    • Label vertex v
    • For all unlabelled neighbors w of v:
      • If (wt[(v,w)] < d[w])
        • d[w] = wt[(v,w)]
        • p[w] = v
  3. Return p

What design choices do we need to make?

 

Put a ⭐ by __________________ operations.

 

Put a 💜 by __________________ operations.

Prim’s Algorithm: Runtime Analysis

  1. Initialize structure:

    • For all v: d[v] = INF, p[v] = null
    • Let d[s] = 0
    • Initialize PQ by d[v]
  2. Repeat n times:

    • Remove minimum d[] unlabelled vertex: v
    • Label vertex v
    • For all unlabelled neighbors w of v: 💜
      • If (wt[(v,w)] < d[w])
        • d[w] = wt[(v,w)]
        • p[w] = v
  3. Return p

\(n\) removeMins + \(\leq m\) decreaseKeys
💜 \(O(m)\) total (adj list)  |  \(O(n^2)\) total (adj matrix)

Adj matrix Adj list
heap \(O(n^2 + m \log n)\) \(O(m \log n)\)
unsorted array \(O(n^2)\) \(O(n^2)\)

 

Which is best? Depends on graph density:

  • Sparse (\(m=O(n)\)):
  • Dense (\(m=O(n^2)\)):

Prim’s Algorithm: Python

import heapq

def prim(graph, start):
    """graph: {vertex: [(neighbor, weight), ...]}"""
    d = {v: float('inf') for v in graph}   # cheapest edge to reach v
    parent = {v: None for v in graph}
    d[start] = 0
    pq = [(0, start)]                       # (edge_weight, vertex)
    visited = set()

    while pq:
        cost, v = heapq.heappop(pq)
        if v in visited:
            continue
        visited.add(v)

        for w, weight in graph[v]:
            if w not in visited and weight < d[w]:
                d[w] = weight              # just the edge weight (not cumulative!)
                parent[w] = v
                heapq.heappush(pq, (weight, w))

    return parent   # MST as parent pointers

Single Source Shortest Path

Given a start vertex (source) \(s\), find the path of least total cost from \(s\) to every vertex in the graph.

Single Source Shortest Path

  • Input: directed graph \(G\) with non-negative edge weights, and a start vertex \(s\).
  • Output: A subgraph \(G’\) consisting of the shortest (minimum total cost) paths from \(s\) to every other vertex in the graph.

Dijkstra’s Algorithm (1959)

 

Note:

SSSP Algorithm

Given a source vertex \(s\), we wish to find the shortest path from \(s\) to every other vertex in the graph.

  1. Initialize structure:

    • d:
    • p:
  2. Repeat these steps:

    • Label a new (unlabelled) vertex \(v\), whose shortest distance has been found
    • Update \(v\)’s neighbors with improved distance and predecessor

SSSP Algorithm

  1. Initialize structure:

    • For all v: d[v] = INF, p[v] = null
    • Let d[s] = 0
    • Initialize PQ by d[v]
  2. Repeat n times:

    • Remove minimum d[] unlabelled vertex: v
    • Label vertex v
    • For all unlabelled neighbors w of v:
      • If (________________ < d[w])
        • d[w] = ________________
        • p[w] = v
  3. Return p

Three Observations:

  • When a node becomes labeled, its shortest distance is final. It will never improve again.

  • d[] values only decrease, never increase.

  • The predecessors p[] form a shortest-path tree.

Your Turn

Execute Dijkstra’s algorithm on this graph: