Sub topic 1
Weighted Undirected Graphs and Their Representations
Every algorithm in this tutorial takes a weighted undirected graph as input. Before we can ask for the cheapest way to connect every vertex, we need a precise model of the graph and a way to store it in Python. This chapter sets up both. The storage choice also affects how fast Prim's and Kruskal's algorithms run later.
Prerequisites
This chapter assumes you already know:
- Graph terminology: vertices, edges, paths, and cycles.
- The basic idea of edge lists and adjacency lists.
- Big-O notation for time and space.
- Basic Python: lists, tuples, list comprehensions, functions, and classes.
- What sorting does, and the rough idea of a priority queue (a container that always hands back its smallest item first).
You do not need any prior knowledge of spanning trees.
The Model: Vertices, Edges, and Weights
A weighted undirected graph G = (V, E, w) has three parts:
- A set of vertices V. We number them 0 to n − 1, where n = |V|.
- A set of edges E. Each edge is an unordered pair {u, v}, so the edge from u to v is the same edge as the one from v to u.
- A weight function w that assigns a number w(u, v) to each edge. Depending on the problem, the number can stand for cable length, cost, latency, or distance.
Because edges are undirected, w(u, v) = w(v, u) always holds. This symmetry is why the minimum spanning tree (MST) problem is defined only for undirected graphs. Directed graphs have a related problem, the minimum spanning arborescence, which needs different algorithms (for example, Chu–Liu/Edmonds) and is not covered here.
What weights are allowed
MST algorithms only compare weights with each other. They never add a weight to a running path length the way shortest-path algorithms do. As a result:
- Zero and negative weights are fine. Dijkstra's algorithm breaks on negative weights, but Prim's and Kruskal's algorithms do not.
- Weights can be integers or floats. Integers avoid rounding surprises when you compare totals.
- Equal weights (ties) are allowed. They affect whether the MST is unique, which a later chapter covers.
Simple graphs, self-loops, and parallel edges
A simple graph has no self-loops (an edge from a vertex to itself) and no parallel edges (two edges joining the same pair of vertices). Real input data often breaks both rules, so you should know what each one means for an MST:
| Feature | Example | Effect on an MST |
|---|---|---|
| Self-loop | edge (0, 0) with weight 2 | It is always a cycle on its own, so it can never be in a spanning tree. It is safe to drop. |
| Parallel edges | (1, 2) with weight 3 and (1, 2) with weight 7 | Only the lightest copy can matter. The heavier copies can be dropped. |
| Isolated vertex | vertex 5 with no edges | The graph is disconnected, so no spanning tree exists. A later chapter handles this with spanning forests. |
A simple undirected graph on n vertices has at most n(n − 1)/2 edges. This bound matters when we reason about density below.
Running Example
The whole tutorial uses one small graph that you can trace by hand. It has 4 vertices and 5 edges.
We will store this one graph in three different ways.
Representation 1: The Edge List
An edge list is a flat list of edges. In this tutorial each edge is a tuple (weight, u, v).
n = 4
edges = [(1, 0, 1), (4, 0, 2), (3, 1, 2), (2, 1, 3), (5, 2, 3)]The weight comes first on purpose. Python compares tuples one element at a time, so sorted(edges) orders the edges by weight and breaks ties by u and then v. Kruskal's algorithm starts with exactly this sort.
Each undirected edge appears once in an edge list. The tuple (1, 0, 1) stands for the edge {0, 1}, and you should not also store (1, 1, 0). If you did, Kruskal's algorithm would still give the right answer, because the second copy would be rejected as a cycle, but it would do twice the sorting work.
Edge lists use O(E) space and are easy to read from files. However, finding the neighbors of a single vertex means scanning the whole list, which costs O(E).
Representation 2: The Adjacency List
An adjacency list stores, for each vertex v, a list of (neighbor, weight) pairs. Prim's algorithm uses this format, because at each step it needs the edges leaving one vertex.
def to_adjacency_list(n, edges):
adj = [[] for _ in range(n)]
for w, u, v in edges:
adj[u].append((v, w))
adj[v].append((u, w)) # undirected: store both directions
return adj
n = 4
edges = [(1, 0, 1), (4, 0, 2), (3, 1, 2), (2, 1, 3), (5, 2, 3)]
adj = to_adjacency_list(n, edges)
for v, nbrs in enumerate(adj):
print(v, nbrs)Output:
0 [(1, 1), (2, 4)]
1 [(0, 1), (2, 3), (3, 2)]
2 [(0, 4), (1, 3), (3, 5)]
3 [(1, 2), (2, 5)]Every undirected edge shows up twice, once in each endpoint's list, so the lists hold 2E entries in total. The space cost is O(V + E). Listing the neighbors of v costs O(deg(v)), where deg(v) is the number of edges touching v.
Converting back to an edge list
Sometimes you have an adjacency list but need an edge list, for example to run Kruskal's algorithm. Because each edge appears twice, keep only one direction, such as the one where u < v:
def to_edge_list(adj):
edges = []
for u, nbrs in enumerate(adj):
for v, w in nbrs:
if u < v:
edges.append((w, u, v))
return edges
adj = [[(1, 1), (2, 4)], [(0, 1), (2, 3), (3, 2)],
[(0, 4), (1, 3), (3, 5)], [(1, 2), (2, 5)]]
print(sorted(to_edge_list(adj)))
# [(1, 0, 1), (2, 1, 3), (3, 1, 2), (4, 0, 2), (5, 2, 3)]The u < v filter also drops self-loops, since a self-loop has u == v.
Representation 3: The Adjacency Matrix
An adjacency matrix is an n × n table where entry [u][v] holds the weight of edge {u, v}. For an undirected graph the matrix is symmetric. You need a value that means "no edge". Using 0 for that is a common bug, because 0 is a valid weight. Use float("inf") instead.
def to_adjacency_matrix(n, edges):
INF = float("inf")
m = [[INF] * n for _ in range(n)]
for i in range(n):
m[i][i] = 0
for w, u, v in edges:
if u != v and w < m[u][v]: # skip self-loops, keep lightest parallel edge
m[u][v] = w
m[v][u] = w
return m
n = 4
edges = [(1, 0, 1), (4, 0, 2), (3, 1, 2), (2, 1, 3), (5, 2, 3)]
for row in to_adjacency_matrix(n, edges):
print(row)Output:
[0, 1, 4, inf]
[1, 0, 3, 2]
[4, 3, 0, 5]
[inf, 2, 5, 0]The matrix uses O(V²) space no matter how many edges exist. It answers "is there an edge between u and v, and what does it weigh?" in O(1) time. Listing a vertex's neighbors costs O(V), because you have to scan the whole row.
Comparing the Representations
| Operation | Edge list | Adjacency list | Adjacency matrix |
|---|---|---|---|
| Space | O(E) | O(V + E) | O(V²) |
| Iterate over all edges | O(E) | O(V + E) | O(V²) |
| Neighbors of v | O(E) | O(deg(v)) | O(V) |
| Weight of edge {u, v} | O(E) | O(deg(u)) | O(1) |
| Sort edges by weight | O(E log E) | needs conversion first | needs conversion first |
| Natural fit | Kruskal | Prim with a heap | Prim on dense graphs, using an array |
Sparse and dense graphs
A graph is sparse when E is close to V, for example road networks, where each intersection has only a few roads. A graph is dense when E is close to the maximum V(V − 1)/2, for example a complete graph of distances between every pair of cities. For a sparse graph with a million vertices, an adjacency matrix would need 10¹² cells, which is far too many, while an adjacency list needs only a few million entries. For a dense graph, both use Θ(V²) space, and the matrix's simple layout and O(1) lookups can win. A later chapter uses this sparse-versus-dense distinction to choose between Prim's and Kruskal's algorithms.
Common Errors and Input Checks
Most MST bugs come from the input, not the algorithm. Here are the usual problems:
- Storing only one direction in an adjacency list. If Prim's algorithm can reach vertex 3 from 1 but never 1 from 3, it may stop early or return a wrong tree.
- Mixing tuple orders. If
(u, v, w)and(w, u, v)both appear in a codebase, sorting by the wrong field fails silently. Choose one order and stick to it. - Vertex labels that are not 0 to n − 1. If the input uses names or labels that start at 1, remap them with a dictionary before building lists indexed by vertex.
- Using 0 to mean "no edge" in a matrix. This blocks zero-weight edges from being used correctly.
- Leaving duplicates in. Parallel edges and self-loops do not break correctness, but they waste time and make hand traces confusing.
A small cleaning function prevents most of these problems:
def normalize_edges(n, edges):
"""Drop self-loops, keep the lightest parallel edge, order endpoints u < v."""
best = {}
for w, u, v in edges:
if not (0 <= u < n and 0 <= v < n):
raise ValueError(f"vertex out of range in edge {(w, u, v)}")
if u == v:
continue
key = (min(u, v), max(u, v))
if key not in best or w < best[key]:
best[key] = w
return [(w, u, v) for (u, v), w in best.items()]
raw = [(1, 0, 1), (9, 1, 0), (4, 0, 2), (3, 2, 1), (2, 1, 3), (5, 2, 3), (7, 3, 3)]
print(sorted(normalize_edges(4, raw)))
# [(1, 0, 1), (2, 1, 3), (3, 1, 2), (4, 0, 2), (5, 2, 3)]Here the raw input has a heavier parallel copy of {0, 1}, an edge written as (2, 1) instead of (1, 2), and a self-loop on vertex 3. After cleaning, the result is exactly the running example.
Exercises
Exercise
An undirected graph has 6 vertices and 9 edges, with no self-loops or parallel edges. How many (neighbor, weight) entries does its adjacency list contain in total, and how many cells does its adjacency matrix have?
Show answer
The adjacency list has 2 × 9 = 18 entries, because each undirected edge is stored once at each endpoint. The adjacency matrix has 6 × 6 = 36 cells, no matter how many edges there are.
Exercise
Why does this tutorial store edges as (weight, u, v) rather than (u, v, weight)?
Show answer
Python compares tuples element by element, so putting the weight first makes sorted(edges) order the edges by weight with no key function. Kruskal's algorithm needs exactly this order.
Exercise
The input contains edges (6, 2, 4) and (3, 4, 2). Which one can matter for a minimum spanning tree, and why?
Show answer
Only (3, 4, 2) can matter. Both join the same pair {2, 4}. A spanning tree uses at most one edge between any two vertices, and swapping the weight-6 copy for the weight-3 copy always lowers the total. The heavier copy can be dropped.
Exercise
You have a complete graph on 2,000 vertices. Roughly how many edges does it have, and is it sparse or dense?
Show answer
It has 2000 × 1999 / 2 = 1,999,000 edges, which is the maximum possible, so the graph is dense. An adjacency matrix with 4,000,000 cells is a reasonable choice here.