Show contents
Chapter 6 of 7 · 25 min
Project: a route planner
By the end of this chapter, you'll be able to
- Represent a weighted graph
- Program Dijkstra's algorithm with a priority queue
- Rebuild the path found
- Adapt the computation when the network changes
The network
The distances below are simplified and rounded for the exercise: do not use them to plan a trip. Each road is recorded in both directions.
roads = [
("Dakar", "Thiès", 70), ("Dakar", "Mbour", 80), ("Thiès", "Mbour", 60),
("Thiès", "Diourbel", 75), ("Thiès", "Saint-Louis", 200), ("Diourbel", "Touba", 45),
("Mbour", "Kaolack", 110), ("Diourbel", "Kaolack", 70), ("Touba", "Saint-Louis", 230),
]
graph = {}
for a, b, km in roads:
graph.setdefault(a, []).append((b, km))
graph.setdefault(b, []).append((a, km))
print(len(graph), "towns")
print("From Thiès:", graph["Thiès"])
7 towns
From Thiès: [('Dakar', 70), ('Mbour', 60), ('Diourbel', 75), ('Saint-Louis', 200)]
Each neighbour is now a pair (town, kilometres): it is a weighted graph. setdefault creates a town's list the first time it is met.
Dijkstra's algorithm
The idea: keep the best known distance to each town, and always process first the town closest to the start among those left. Once a town is processed, its distance is final: no detour through a farther town can do better, since distances are positive.
To find quickly “the closest one left”, we use a priority queue: the heapq module keeps a list where the smallest item always comes out first, in O(log n).
import heapq
roads = [
("Dakar", "Thiès", 70), ("Dakar", "Mbour", 80), ("Thiès", "Mbour", 60),
("Thiès", "Diourbel", 75), ("Thiès", "Saint-Louis", 200), ("Diourbel", "Touba", 45),
("Mbour", "Kaolack", 110), ("Diourbel", "Kaolack", 70), ("Touba", "Saint-Louis", 230),
]
graph = {}
for a, b, km in roads:
graph.setdefault(a, []).append((b, km))
graph.setdefault(b, []).append((a, km))
def dijkstra(graph, start, goal):
distance = {start: 0}
previous = {start: None}
queue = [(0, start)]
done = set()
while queue:
d, town = heapq.heappop(queue)
if town in done:
continue
done.add(town)
if town == goal:
break
for neighbour, km in graph[town]:
new = d + km
if new < distance.get(neighbour, float("inf")):
distance[neighbour] = new
previous[neighbour] = town
heapq.heappush(queue, (new, neighbour))
if goal not in distance:
return None, []
path, town = [], goal
while town is not None:
path.append(town)
town = previous[town]
return distance[goal], path[::-1]
print(dijkstra(graph, "Dakar", "Kaolack"))
print(dijkstra(graph, "Dakar", "Touba"))
print(dijkstra(graph, "Mbour", "Saint-Louis"))
(190, ['Dakar', 'Mbour', 'Kaolack'])
(190, ['Dakar', 'Thiès', 'Diourbel', 'Touba'])
(260, ['Mbour', 'Thiès', 'Saint-Louis'])
heapq.heappopalways takes out the pair with the smallest distance: the town closest to the start;- a town can be added to the queue several times, when a better distance is found for it;
donelets you ignore the old entries; - we stop as soon as the goal is processed: its distance is then final;
- with a priority queue, the algorithm is O((V + E) log V), for V towns and E roads.
Kaolack is the closest of the remaining towns: its distance is final.
Text description of the animation
- We process Dakar: its neighbours get a first distance.
- Thiès is the closest (70): we process it. Mbour via Thiès would be 130, worse than 80: no change.
- Mbour (80) is processed next: Kaolack gets 80 + 110 = 190.
- Diourbel (145): going through it would give 215 for Kaolack, more than 190. We keep 190.
- Kaolack is the closest of the remaining towns: its distance is final.
Mini-lab: your own networkPython 3.13
Output
Click “Run”: Python will load in your browser (about 10 MB the first time).Your code runs in your browser, isolated from the page. · Ctrl/⌘ + Enter to run · Esc then Tab to leave the editor
Your turn
Worked exercise
Worked exercise: the closed road
Roadworks close the Thiès–Diourbel road. Write a function without_road(roads, a, b) that returns the list of roads without this one (in either direction), rebuild the graph and compute the new route from Dakar to Touba. How many extra kilometres?
Hint 1
{start, end} differs from {a, b} works in both directions.Hint 2
dijkstra as is: only the graph changes.Show the solution and common mistakes
import heapq
roads = [
("Dakar", "Thiès", 70), ("Dakar", "Mbour", 80), ("Thiès", "Mbour", 60),
("Thiès", "Diourbel", 75), ("Thiès", "Saint-Louis", 200), ("Diourbel", "Touba", 45),
("Mbour", "Kaolack", 110), ("Diourbel", "Kaolack", 70), ("Touba", "Saint-Louis", 230),
]
def build(roads):
graph = {}
for a, b, km in roads:
graph.setdefault(a, []).append((b, km))
graph.setdefault(b, []).append((a, km))
return graph
def dijkstra(graph, start, goal):
distance, previous, queue = {start: 0}, {start: None}, [(0, start)]
while queue:
d, v = heapq.heappop(queue)
if d > distance[v]:
continue
for w, km in graph[v]:
if d + km < distance.get(w, float("inf")):
distance[w], previous[w] = d + km, v
heapq.heappush(queue, (d + km, w))
path, v = [], goal
while v is not None:
path.append(v)
v = previous[v]
return distance[goal], path[::-1]
def without_road(roads, a, b):
return [r for r in roads if {r[0], r[1]} != {a, b}]
before = dijkstra(build(roads), "Dakar", "Touba")
after = dijkstra(build(without_road(roads, "Thiès", "Diourbel")), "Dakar", "Touba")
print("before:", before)
print("after:", after)
print("detour:", after[0] - before[0], "km")
before: (190, ['Dakar', 'Thiès', 'Diourbel', 'Touba'])
after: (305, ['Dakar', 'Mbour', 'Kaolack', 'Diourbel', 'Touba'])
detour: 115 km
The new route goes round through Mbour and Kaolack. The variant of dijkstra used here replaces the done set with the test d > distance[v], which ignores stale queue entries in the same way.
Common mistakes:
- Only removing
("Thiès", "Diourbel", 75)from the graph in one direction: the road would remain in the other, sincebuildadds it to both towns. It must be removed before building the graph. - Changing the original
roadslist: later computations (such as “before”) would be skewed. Return a new list.
Summary
- 1In a weighted graph, each edge carries a weight: distance, time, cost.
- 2Dijkstra always processes the town closest to the start; its distance then becomes final.
- 3A priority queue (heapq) gives that town in O(log n): the algorithm is O((V + E) log V).
- 4Remembering each vertex's predecessor lets you rebuild the path.
- 5Breadth-first search is unsuitable for different weights, and Dijkstra requires positive weights.
Your progress is saved on this device. Create a free account to keep your progress on all your devices.