Weighted graphs: when roads have prices
🌍 In real life. A city's buses run between six stops, and every leg has its own fare: 4 taka from A to B, 2 taka from A to C, and so on. Going from A to D, the route with the fewest buses is not always the cheapest. The cheapest route might change buses more often but pay less in total.
The idea in one sentence: a weighted graph gives every edge a number, its weight (a fare, a distance, a time), and a path's cost is the sum of its weights, so "shortest" now means "cheapest", not "fewest edges".
Its words:
- weight: the number on an edge; here, a fare
- path cost (path length): the sum of the weights along a path
- shortest path: a path from a to b with the smallest cost
- weighted adjacency list: in Python, a dict from each stop to a list of
(neighbour, weight)pairs
Step by step, from the list of roads to a graph:
- start with an empty dict
- for each road
(a, b, fare): add(b, fare)to a's list and(a, fare)to b's list - sort each list, so neighbours come in the same order every time
Why can't BFS (Lesson 51.2) find the cheapest route? Watch it on the same stops, ignoring fares: it reaches D in 2 roads, A → B → D, which costs 4 + 5 = 9 taka. But A → C → B → D takes 3 roads and costs only 2 + 1 + 5 = 8.
Why BFS is not enough. BFS settles places in order of the number of edges, which is right when every edge costs the same. With different weights, a path with more edges can be cheaper, and BFS has already fixed its answer before it sees that path. Chapter 54's next lesson, Dijkstra's algorithm, settles places in order of cost instead.
What it costs, by counting. The weighted list stores each road twice, once from each end, with its weight: for 9 roads, 18 (stop, fare) pairs, 2E in general, plus one list per stop: O(V + E) memory. Adding up a route of k legs takes k look-ups in the stops' lists.
def build_weighted(roads):
graph = {}
for a, b, fare in roads:
graph.setdefault(a, []).append((b, fare)) # both ways,
graph.setdefault(b, []).append((a, fare)) # with the same fare
for v in graph:
graph[v].sort()
return graph
roads = [("A", "B", 4), ("A", "C", 2), ("B", "C", 1), ("B", "D", 5), ("C", "D", 8),
("C", "E", 10), ("D", "E", 2), ("D", "F", 6), ("E", "F", 3)]
graph = build_weighted(roads)
print(graph["C"])
def route_cost(graph, route):
total = 0
for a, b in zip(route, route[1:]):
total += dict(graph[a])[b] # the fare from a to b
return total
print(route_cost(graph, ["A", "B", "D"]), route_cost(graph, ["A", "C", "B", "D"]))Mistakes and edge cases.
- adding the road one way only: for two-way roads the fare goes into both lists; a one-way road (a directed edge) goes into one
- two roads between the same stops: keep the cheaper one, or both, but be sure which;
dict(graph[a])[b]keeps only the last one listed - a route with a missing leg: looking up a stop that isn't a neighbour stops with a KeyError; check first and report "no route"
- weights that aren't costs: a probability or a capacity combines differently (multiplied, or the smallest), so "add up the weights" isn't always the rule
Quiz
What does this print?
def build_weighted(roads): graph = {} for a, b, fare in roads: graph.setdefault(a, []).append((b, fare)) # both ways, graph.setdefault(b, []).append((a, fare)) # with the same fare for v in graph: graph[v].sort() return graph g = build_weighted([("X", "Y", 7), ("Y", "Z", 3)]) print(g["Y"])On the bus map, BFS from A reaches D by A → B → D. What is wrong with that as the cheapest route?
- BFS counts roads, not fares: A → C → B → D costs 8, not 9
- Nothing: fewer roads is always cheaper
- BFS can't reach D
What does this print?
graph = {"A": [("B", 4), ("C", 2)], "B": [("A", 4), ("C", 1)], "C": [("A", 2), ("B", 1)]} total = 0 route = ["B", "C", "A"] for a, b in zip(route, route[1:]): total += dict(graph[a])[b] print(total)A graph has 50 two-way roads. How many (neighbour, weight) pairs does its weighted adjacency list hold?
- 100
- 50
- 2,500
graph["B"] is missing A, although the road A–B costs 4. Which line is wrong?
def build_weighted(roads): graph = {} for a, b, fare in roads: graph.setdefault(a, []).append((b, fare)) graph.setdefault(b, []) return graph
Coding tasks
Write
build_weighted(roads): each road is(a, b, fare), usable both ways. Return a dict from each stop to the sorted list of its(neighbour, fare)pairs.Write
route_cost(graph, route): the total fare of travelling alongroute, a list of stops. ReturnNoneif some leg has no road. A route of one stop costs 0.