Final project: a route planner for city buses
🌍 In real life. Rahim wants to get from Farmgate to Uttara by city bus. A direct bus costs 20 taka, but changing at Gulshan costs 12 + 5 = 17 taka. A journey planner on his phone must answer two different questions: which route has the fewest changes, and which is cheapest? This last project builds that planner from pieces you already know.
The idea in one sentence: store the bus network as a graph (stops are vertices, bus legs are weighted edges), answer "fewest legs" with BFS (Chapter 51), "cheapest fare" with Dijkstra (Chapter 54), and rebuild the actual route by remembering where each stop was reached from.
Its words:
- bus map: a dict from each stop to a list of
(next stop, fare)pairs, both directions (an adjacency list, Chapter 51) - leg: one bus ride between two neighbouring stops
- came_from: a dict from each stop to the stop it was reached from on the best route found
Step by step:
- build the bus map from the list of legs, adding each leg in both directions
- fewest legs: BFS from the start; every leg counts 1
- cheapest fare: Dijkstra from the start, with a heap of
(fare so far, stop) - route: whenever a stop gets a cheaper fare, record
came_from[stop]; at the goal, followcame_fromback to the start and reverse
In the animations the stops are letters: A Farmgate, B Shahbagh, C Mirpur, D Motijheel, E Gulshan, F Uttara. First, BFS counts legs, so the direct bus to F looks best:
Now with fares. Dijkstra settles the cheapest stop first; when Gulshan (E) is settled at 12 taka, Uttara (F) drops from 20 to 17, and the old (20, F) entry is skipped later:
Why each piece is the right tool. BFS finds the fewest legs because it settles all stops one leg away, then all two legs away, and so on (Lesson 51.2). It ignores fares, so it can't find the cheapest trip. Dijkstra is right for fares because no fare is negative: once the cheapest unsettled stop is taken from the heap, no later route can reach it more cheaply (Lesson 54.2). The route comes from came_from: each stop remembers the stop that gave it its final fare, and following those links from the goal walks the cheapest route backwards.
What it costs, by counting. For a city with V stops and E legs, building the map touches each leg twice: O(V + E). BFS is O(V + E). Dijkstra pushes at most one heap entry per improvement, so O((V + E) log V). For 2,000 stops and 6,000 legs that is about 8,000 × 11, roughly 88,000 steps, under a tenth of a second in Python. Rebuilding the route walks back along it once, O(V) at worst. Memory is O(V + E) for the map plus O(V) for best, came_from and the heap's live entries.
def build_bus_map(legs):
bus_map = {}
for a, b, fare in legs:
bus_map.setdefault(a, []).append((b, fare)) # a bus runs both ways
bus_map.setdefault(b, []).append((a, fare))
for stop in bus_map:
bus_map[stop].sort() # a fixed order, so every run is the same
return bus_map
from collections import deque
def fewest_legs(bus_map, start, goal):
legs = {start: 0}
queue = deque([start])
while queue: # BFS: every leg counts the same
stop = queue.popleft()
if stop == goal:
return legs[stop]
for nxt, _ in bus_map[stop]:
if nxt not in legs:
legs[nxt] = legs[stop] + 1
queue.append(nxt)
return -1
import heapq
def plan_route(bus_map, start, goal):
best = {start: 0}
came_from = {start: None} # the stop each stop was reached from
heap = [(0, start)]
done = set()
while heap:
fare, stop = heapq.heappop(heap)
if stop in done:
continue
done.add(stop)
if stop == goal:
route = []
while stop is not None: # walk the arrows back to the start
route.append(stop)
stop = came_from[stop]
return fare, route[::-1]
for nxt, cost in bus_map.get(stop, []):
if nxt not in done and fare + cost < best.get(nxt, float("inf")):
best[nxt] = fare + cost
came_from[nxt] = stop
heapq.heappush(heap, (fare + cost, nxt))
return -1, []
legs = [("Farmgate", "Shahbagh", 10), ("Farmgate", "Mirpur", 15), ("Farmgate", "Gulshan", 12),
("Farmgate", "Uttara", 20), ("Shahbagh", "Motijheel", 8), ("Mirpur", "Gulshan", 6),
("Mirpur", "Uttara", 14), ("Gulshan", "Motijheel", 9), ("Gulshan", "Uttara", 5)]
bus_map = build_bus_map(legs)
print(bus_map["Uttara"])
print(fewest_legs(bus_map, "Farmgate", "Uttara"))
print(plan_route(bus_map, "Farmgate", "Uttara"))
print(plan_route(bus_map, "Farmgate", "Motijheel"))Mistakes and edge cases.
- adding a leg in one direction only: buses run both ways; a one-way map can make a stop unreachable
- BFS for fares: it finds the fewest legs, which here is the dearer direct bus
- recording
came_fromfor every neighbour seen: only record it when the fare improves, or the route will not match the fare - forgetting to reverse: walking
came_fromgives the route from the goal back to the start - start equal to goal, or a stop not on the map: a fare of 0 with the one-stop route, and −1 with no route
🎉 You have finished the course. From your first print to a route planner built from graphs, heaps and dicts, you now know the patterns behind most interview problems. Keep them sharp with the practice chests at the end of every chapter: each one points to LeetCode problems chosen for exactly that chapter's ideas.
Quiz
Rahim wants the trip with the fewest bus changes. Which algorithm?
- BFS: every leg counts the same
- Dijkstra with the fares
- Sorting the legs by fare
What does this print?
def build_bus_map(legs): bus_map = {} for a, b, fare in legs: bus_map.setdefault(a, []).append((b, fare)) # a bus runs both ways bus_map.setdefault(b, []).append((a, fare)) for stop in bus_map: bus_map[stop].sort() # a fixed order, so every run is the same return bus_map import heapq def cheapest_fare(bus_map, start, goal): best = {start: 0} heap = [(0, start)] done = set() while heap: fare, stop = heapq.heappop(heap) # the cheapest stop not settled yet if stop in done: continue done.add(stop) if stop == goal: return fare for nxt, cost in bus_map.get(stop, []): if nxt not in done and fare + cost < best.get(nxt, float("inf")): best[nxt] = fare + cost heapq.heappush(heap, (fare + cost, nxt)) return -1 bus_map = build_bus_map([("Farmgate", "Shahbagh", 10), ("Farmgate", "Mirpur", 15), ("Farmgate", "Gulshan", 12), ("Farmgate", "Uttara", 20), ("Shahbagh", "Motijheel", 8), ("Mirpur", "Gulshan", 6), ("Mirpur", "Uttara", 14), ("Gulshan", "Motijheel", 9), ("Gulshan", "Uttara", 5)]) print(cheapest_fare(bus_map, "Shahbagh", "Uttara"), cheapest_fare(bus_map, "Mirpur", "Mirpur"))What is the time of Dijkstra with a heap on V stops and E legs?
- O((V + E) log V)
- O(V + E)
- O(V × E)
When should came_from[next] be set?
- Only when next gets a cheaper fare through the current stop
- Every time next is seen
- Only for the goal
build_bus_map makes Uttara unreachable from Farmgate when the only leg is listed as ("Uttara", "Farmgate", 20). Which line is wrong?
def build_bus_map(legs): bus_map = {} for a, b, fare in legs: bus_map.setdefault(a, []).append((b, fare)) bus_map.setdefault(b, []) for stop in bus_map: bus_map[stop].sort() return bus_map
Coding tasks
Write
build_bus_map(legs):legsis a list of(stop, stop, fare)triples. Return a dict from every stop to a sorted list of(neighbour, fare)pairs, adding each leg in both directions.Write
cheapest_fare(bus_map, start, goal): the smallest total fare fromstarttogoalon a bus map like the one from the first task, or-1ifgoalcan't be reached (or isn't on the map). No fare is negative. The starter already includesbuild_bus_mapfrom the first task.Write
plan_route(bus_map, start, goal): return a tuple(fare, stops), the cheapest total fare and the list of stops along that route fromstarttogoal, or(-1, [])if there is no route. Every test has only one cheapest route. The starter already includesbuild_bus_map.