Sub topic 3
Weighted and unweighted graphs
This chapter assumes you know Python lists, dictionaries, and sets, and that you have met Big-O notation. It builds on the earlier chapters on vertices, edges, and directed and undirected edges.
Unweighted graphs
In an unweighted graph, an edge only says that two vertices are connected. All edges count the same. A friendship network is a typical example. Two people are either friends or not.
The length of a path in an unweighted graph is its number of edges. The A-B-D path has length 2.
Weighted graphs
In a weighted graph, each edge carries a number called its weight. The weight can mean distance, cost, time, capacity, or similarity. The meaning depends on the problem. A road map is a typical example. Each edge is a road, and its weight is the length in kilometers.
The weight of a path is the sum of the weights of its edges. A path with fewer edges is not always the cheaper one.
Compare two paths from A to D:
| Path | Edges | Total weight |
|---|---|---|
| A, C, D | 2 | 1 + 5 = 6 |
| A, C, B, D | 3 | 1 + 2 + 2 = 5 |
The path with three edges is cheaper than the path with two. If you only count edges, you pick the wrong route. This is why the distinction matters. An unweighted graph asks for the fewest edges. A weighted graph asks for the lowest total weight.
Storing weights
An edge list needs a third value per edge, and an adjacency list needs to store the weight with each neighbor. The next chapters cover each structure in detail. For now, here is the dictionary-of-dictionaries form for the graph above.
wgraph = {
"A": {"B": 4, "C": 1},
"B": {"D": 2},
"C": {"B": 2, "D": 5},
"D": {},
}
def path_weight(graph, path):
total = 0
for u, v in zip(path, path[1:]):
total += graph[u][v] # KeyError if the edge does not exist
return total
print(path_weight(wgraph, ["A", "C", "D"])) # 6
print(path_weight(wgraph, ["A", "C", "B", "D"])) # 5The outer key is the source vertex. The inner dictionary maps each neighbor to the weight of the edge. Looking up wgraph["A"]["B"] takes constant time on average.
Treating an unweighted graph as weighted
You can store an unweighted graph in the same structure by giving every edge weight 1. Then the path weight equals the number of edges. This lets one piece of code handle both kinds. It costs extra memory, so many programs keep the unweighted form when weights would carry no information.
Common errors
- Using 0 for "no edge" when 0 is a valid weight. An edge of weight 0 and a missing edge then look the same. In a matrix, use
Noneorfloat("inf")for a missing edge when weights can be 0. - Assuming the path with fewest edges is cheapest. This holds only when all weights are equal. Breadth-first search, covered later, finds fewest edges, so it gives the cheapest path only on unweighted graphs, or when all weights are equal.
- Ignoring negative weights. A weight can be negative, for example a refund or an elevation drop. Some shortest-path algorithms fail on negative weights, so check the data before choosing one.
- Mixing up weight and direction. Weight is a property of an edge. Direction is a separate property. A graph can be directed and unweighted, undirected and weighted, or any other combination.
Exercise
In the graph above, what is the cheapest path from A to B, and what is its weight? Is it the path with the fewest edges?
Show answer
The cheapest path is A, C, B with weight 1 + 2 = 3. The direct edge A to B has weight 4 and only one edge, so the path with the fewest edges is not the cheapest.
Exercise
Why does path_weight(wgraph, ["B", "A"]) fail, and what does that tell you about the graph?
Show answer
It raises a KeyError because wgraph["B"] has no key "A". The graph is directed, so the edge A to B exists but B to A does not.