Sub topic 1
Weighted Undirected Graphs and Their Representations
Every algorithm in this tutorial takes a weighted undirected graph as input. This chapter fixes the vocabulary and the two data layouts that Kruskal's and Prim's algorithms expect. It also covers the mistakes that most often break MST code before the algorithm even runs.
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, functions, and classes.
The working model
A weighted undirected graph is a set of vertices V and a set of edges E. Each edge connects two vertices and carries a number called its weight. "Undirected" means the edge {u, v} is the same edge as {v, u}, so it can be crossed in either direction. A weight usually stands for a cost such as cable length, latency, or money.
This tutorial uses these conventions throughout:
- Vertices are numbered
0ton - 1, so they can index Python lists directly. - V is the number of vertices and E is the number of edges.
- Weights are comparable numbers. Negative weights are allowed for MSTs, unlike for some shortest-path algorithms.
Here is the running example, a graph with four vertices and five edges:
Two representations
Kruskal's algorithm works on an edge list, a flat list of (weight, u, v) tuples. Putting the weight first means that sorted(edges) orders the edges by weight with no key function.
Prim's algorithm works on an adjacency list, where adj[v] holds (neighbor, weight) pairs for every edge touching v. Because the graph is undirected, each edge appears twice: once in each endpoint's list.
edges = [(1, 0, 1), (4, 0, 2), (3, 1, 2), (2, 1, 3), (5, 2, 3)]
n = 4
def to_adjacency(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
adj = to_adjacency(n, edges)
for v, neighbors in enumerate(adj):
print(v, neighbors)
# 0 [(1, 1), (2, 4)]
# 1 [(0, 1), (2, 3), (3, 2)]
# 2 [(0, 4), (1, 3), (3, 5)]
# 3 [(1, 2), (2, 5)]A third option is an adjacency matrix, a V × V grid where cell [u][v] holds the weight or None. It uses O(V²) memory. That cost only pays off for dense graphs, which come up again in the chapter on choosing between Prim and Kruskal.
| Representation | Space | Natural fit |
|---|---|---|
| Edge list | O(E) | Kruskal (sort all edges) |
| Adjacency list | O(V + E) | Prim with a heap |
| Adjacency matrix | O(V²) | Dense graphs, simple array-based Prim |
Common errors
- Off-by-one vertex IDs. Input files often number vertices from 1. Subtract 1 when you read them in, or allocate
n + 1slots and ignore index 0. - Wrong tuple order. If edges are stored as
(u, v, w),sorted(edges)sorts byuinstead of by weight. Either keep weight first or sort withkey=lambda e: e[2]. - Self-loops. An edge
(w, v, v)can never belong to a spanning tree. You can drop it when loading the graph. - Parallel edges. Two edges between the same pair are legal. Both algorithms handle them correctly, but only the lighter one can ever be chosen.
Exercise
A file lists the undirected edges "1 2 7", "2 3 4", and "1 3 9" as (u, v, weight), with vertices numbered from 1. Write the edge list in this tutorial's (weight, u, v) convention, and give the adjacency list entry adj[0].
Show answer
Subtracting 1 from each vertex ID gives edges = [(7, 0, 1), (4, 1, 2), (9, 0, 2)]. Vertex 0 touches the first and third edges, so adj[0] = [(1, 7), (2, 9)].
Exercise
A graph has V = 1,000 vertices and E = 3,000 edges. Roughly how many stored entries does an adjacency list need compared with an adjacency matrix?
Show answer
An adjacency list stores 2E = 6,000 neighbor entries, plus 1,000 list headers. An adjacency matrix stores V² = 1,000,000 cells. The list is far smaller for this sparse graph.