Sub topic 10
Storing weights and direction in each representation
This chapter assumes you know what a graph is, the difference between directed and undirected edges, what a weight is, and the three basic structures: edge list, adjacency matrix, and adjacency list. Here you learn how each structure records direction and weight, and the mistakes that come with each.
Direction
An undirected edge {u, v} is a single connection that works both ways. A directed edge u -> v works one way only. Each structure handles this differently.
- Edge list: store one pair per edge. For a directed graph, the pair
(u, v)meansu -> v, so order matters. For an undirected graph, treat(u, v)and(v, u)as the same edge. - Adjacency matrix: for a directed edge, set only
matrix[u][v]. For an undirected edge, set bothmatrix[u][v]andmatrix[v][u], so the matrix is symmetric. - Adjacency list: for a directed edge, append
vtograph[u]only. For an undirected edge, also appendutograph[v].
The most common bug is forgetting the reverse entry in an undirected graph. Traversals then reach some vertices from one side but not the other.
Weights
A weight is a value attached to an edge, such as a distance or a cost.
- Edge list: use triples
(u, v, w). - Adjacency matrix: store the weight in the cell instead of
1. - Adjacency list: store
(neighbor, weight)pairs, or use a dictionary of dictionaries.
The matrix needs a value that means "no edge". Using 0 is risky, because 0 can be a real weight. Use None or float("inf") instead.
INF = float("inf")
nodes = ["A", "B", "C", "D"]
index = {name: i for i, name in enumerate(nodes)}
n = len(nodes)
# Directed, weighted edges: (from, to, weight)
edges = [("A", "B", 4), ("A", "C", 1), ("C", "B", 2), ("B", "D", 2), ("C", "D", 5)]
# Edge list: already holds the triples.
# Adjacency matrix: INF means "no edge".
matrix = [[INF] * n for _ in range(n)]
for u, v, w in edges:
matrix[index[u]][index[v]] = w # directed: set one cell only
# Adjacency list: dict of dicts.
wgraph = {name: {} for name in nodes}
for u, v, w in edges:
wgraph[u][v] = w
print(matrix[index["A"]][index["B"]]) # 4
print(matrix[index["B"]][index["A"]]) # inf, no edge B -> A
print(wgraph["A"]) # {'B': 4, 'C': 1}
print(wgraph["D"]) # {}Note that wgraph is created with an entry for every vertex, so a vertex with no outgoing edges (like D) still appears with an empty dictionary. Without that, wgraph["D"] would raise a KeyError during the three compare
| Structure | Direction | Weight | Weight lookup |
|---|---|---|---|
| Edge list | Pair order | Third tuple item | Linear scan |
| Adjacency matrix | One cell or two | Cell value | Constant time |
| Adjacency list (dict of dicts) | One entry or two | Inner dict value | Constant time on average |
Common errors
- Using
0for "no edge" in a weighted matrix. A zero-weight edge becomes indistinguishable from a missing one. - Writing only one direction for an undirected weighted edge. You must store the same weight in both places, or the two directions can disagree.
- Checking
graph[v]for a vertex that has no entry. Usedefaultdictor pre-create every vertex. - Comparing weights without a sentinel in mind. With
INFfor missing edges, a minimum search over a row works naturally. WithNoneit raises aTypeErrorin Python 3.
Exercise
In a directed graph stored as a weighted adjacency matrix, the edge B -> A has weight 0 and there is no edge A -> B. You use 0 to mean "no edge". What goes wrong, and what is a safer choice?
Show answer
matrix[B][A] and matrix[A][B] both hold 0, so you can't tell the real zero-weight edge B -> A from the missing edge A -> B. Use a sentinel that can't be a weight, such as float("inf") or None, for "no edge".
Exercise
Write the adjacency-list dictionary of dictionaries for an undirected graph with one edge between "X" and "Y" of weight 7.
Show answer
{"X": {"Y": 7}, "Y": {"X": 7}}. The weight is stored once in each endpoint's inner dictionary.