Mini Project: A Route Planner
A route planner answers one question many times: what is the best way from here to there? Behind the map sits a weighted graph, and every algorithm of this course's shortest-path sections can answer the question. They differ in what they assume, how much work they do and what else they compute along the way. In this project you build a small planner for a map of ten towns, answer the same queries with BFS, Dijkstra, a goal-directed variant of Dijkstra (A*), Bellman-Ford and Floyd-Warshall, check that they agree, and count their work.
The project puts the course to work: BFS, Dijkstra and its priority queues, Bellman-Ford, Floyd-Warshall and the potentials of Johnson's algorithm. Each step is a complete program; later steps repeat the map, so you can run any of them on its own.
The map
Ten towns to have coordinates on a 100 km by 100 km square, and 17 roads join them. Each road's length is the straight-line distance between its towns rounded up to whole kilometres, so no road is shorter than the straight line, a fact Step 3 relies on.
Step 1: Fewest roads versus fewest kilometres
The first version stores the map and answers the query from to twice: with BFS, which minimizes the number of roads, and with Dijkstra, which minimizes kilometres.
import heapq, math
from collections import deque
towns = {"A": (5, 50), "B": (25, 20), "C": (25, 80), "D": (45, 45), "E": (50, 10),
"F": (55, 85), "G": (70, 35), "H": (75, 65), "I": (95, 20), "J": (95, 75)}
roads = "AB AC AD BD BE CD CF DG DH EG EI FH FJ GI GH HJ IJ".split()
adj = {t: [] for t in towns}
for u, v in roads:
km = math.ceil(math.dist(towns[u], towns[v]))
adj[u].append((v, km)); adj[v].append((u, km))
for t in adj:
adj[t].sort()
def route(parent, t):
path = [t]
while parent[path[-1]]:
path.append(parent[path[-1]])
return path[::-1]
def length(path):
return sum(dict(adj[u])[v] for u, v in zip(path, path[1:]))
def bfs(s):
parent, q = {s: None}, deque([s])
while q:
u = q.popleft()
for v, _ in adj[u]:
if v not in parent:
parent[v] = u; q.append(v)
return parent
def dijkstra(s):
d, parent, done, pq = {s: 0}, {s: None}, set(), [(0, s)]
while pq:
du, u = heapq.heappop(pq)
if u in done:
continue
done.add(u)
for v, w in adj[u]:
if v not in d or du + w < d[v]:
d[v], parent[v] = du + w, u
heapq.heappush(pq, (d[v], v))
return d, parent
p1 = route(bfs("A"), "J")
d, parent = dijkstra("A")
p2 = route(parent, "J")
print(f"fewest roads: {' -> '.join(p1)} ({len(p1) - 1} roads, {length(p1)} km)")
print(f"fewest kilometres: {' -> '.join(p2)} ({len(p2) - 1} roads, {length(p2)} km)")
print("distances from A:", d)fewest roads: A -> C -> F -> J (3 roads, 110 km)
fewest kilometres: A -> D -> H -> J (3 roads, 101 km)
distances from A: {'A': 0, 'B': 37, 'C': 37, 'D': 41, 'E': 64, 'F': 68, 'G': 68, 'H': 78, 'I': 98, 'J': 101}
Step 2: Counting Dijkstra's work
A planner that serves many users cares about work per query. This version counts edge looks (adjacency-list entries examined) and heap operations, and stops as soon as the destination is settled, which is correct because a settled vertex's distance is final (correctness proof).
import heapq, math
towns = {"A": (5, 50), "B": (25, 20), "C": (25, 80), "D": (45, 45), "E": (50, 10),
"F": (55, 85), "G": (70, 35), "H": (75, 65), "I": (95, 20), "J": (95, 75)}
roads = "AB AC AD BD BE CD CF DG DH EG EI FH FJ GI GH HJ IJ".split()
adj = {t: [] for t in towns}
for u, v in roads:
km = math.ceil(math.dist(towns[u], towns[v]))
adj[u].append((v, km)); adj[v].append((u, km))
def dijkstra(s, t=None):
d, done, pq = {s: 0}, [], [(0, s)]
looks = heap_ops = 0
while pq:
du, u = heapq.heappop(pq); heap_ops += 1
if u in done:
continue
done.append(u)
if u == t:
break
for v, w in adj[u]:
looks += 1
if v not in d or du + w < d[v]:
d[v] = du + w
heapq.heappush(pq, (d[v], v)); heap_ops += 1
return d, done, looks, heap_ops
for s, t in [("A", "J"), ("A", "D"), ("E", "C")]:
d, done, looks, ops = dijkstra(s, t)
print(f"{s} -> {t}: {d[t]} km; settled {len(done)} towns ({''.join(done)}), {looks} edge looks, {ops} heap operations")
d, done, looks, ops = dijkstra("A")
print(f"all towns from A: {looks} edge looks, {ops} heap operations")A -> J: 101 km; settled 10 towns (ABCDEFGHIJ), 31 edge looks, 21 heap operations
A -> D: 41 km; settled 4 towns (ABCD), 9 edge looks, 9 heap operations
E -> C: 101 km; settled 10 towns (EBGIDAHJFC), 31 edge looks, 20 heap operations
all towns from A: 34 edge looks, 23 heap operations
The early stop helps a lot for nearby destinations: settles only the towns closer to than . For the far corner every town is settled, because Dijkstra expands in circles around the source and does not know where the destination is.
Step 3: Aiming at the destination
A* search gives Dijkstra a sense of direction. It orders the queue by , where is the straight-line distance from to the destination. Why is that still correct? It is exactly Dijkstra on the reweighted graph , the reweighting of Johnson's algorithm with potential . Every path from to shifts by the same amount , so shortest paths are preserved, and the new weights are non-negative because a road is never shorter than the straight line: by the triangle inequality. A heuristic with this property is called consistent.
import heapq, math
towns = {"A": (5, 50), "B": (25, 20), "C": (25, 80), "D": (45, 45), "E": (50, 10),
"F": (55, 85), "G": (70, 35), "H": (75, 65), "I": (95, 20), "J": (95, 75)}
roads = "AB AC AD BD BE CD CF DG DH EG EI FH FJ GI GH HJ IJ".split()
adj = {t: [] for t in towns}
for u, v in roads:
km = math.ceil(math.dist(towns[u], towns[v]))
adj[u].append((v, km)); adj[v].append((u, km))
def search(s, t, use_h):
h = (lambda v: math.dist(towns[v], towns[t])) if use_h else (lambda v: 0)
assert all(w >= h(u) - h(v) for u in adj for v, w in adj[u]) # consistency
d, parent, done, pq, looks = {s: 0}, {s: None}, [], [(h(s), s)], 0
while pq:
_, u = heapq.heappop(pq)
if u in done:
continue
done.append(u)
if u == t:
break
for v, w in adj[u]:
looks += 1
if v not in d or d[u] + w < d[v]:
d[v], parent[v] = d[u] + w, u
heapq.heappush(pq, (d[v] + h(v), v))
path = [t]
while parent[path[-1]]:
path.append(parent[path[-1]])
return d[t], "".join(path[::-1]), "".join(done), looks
for s, t in [("A", "J"), ("A", "I"), ("C", "E")]:
for name, use_h in [("Dijkstra", False), ("A*", True)]:
km, path, done, looks = search(s, t, use_h)
print(f"{s} -> {t} {name:8}: {km} km via {path}; settled {len(done):2} ({done}), {looks} edge looks")A -> J Dijkstra: 101 km via ADHJ; settled 10 (ABCDEFGHIJ), 31 edge looks
A -> J A* : 101 km via ADHJ; settled 4 (ADHJ), 12 edge looks
A -> I Dijkstra: 98 km via ADGI; settled 9 (ABCDEFGHI), 28 edge looks
A -> I A* : 98 km via ADGI; settled 4 (ADGI), 12 edge looks
C -> E Dijkstra: 101 km via CDGE; settled 10 (CFADHGJBIE), 31 edge looks
C -> E A* : 101 km via CDGE; settled 6 (CDAGBE), 18 edge looks
Both searches return the same routes and lengths, but A* settles fewer towns, because towns that lie away from the destination get a large and wait at the back of the queue. On real road maps the savings are far larger, and production planners go further still with precomputed landmarks or contraction hierarchies.
Step 4: Negative edges and the whole table
Suppose the planner measures cost instead of distance, and a regional scheme refunds drivers 40 cost units for using the new bypass from to , in that direction only. That road becomes one-way with cost , and Dijkstra is no longer guaranteed to be right. Bellman-Ford handles the negative edge, and Floyd-Warshall gives the whole cost table at once. The program turns every other road into two arcs, checks that there is no negative cycle (any cycle through must come back from to , which costs at least 27), and compares the results and the work.
import heapq, math
towns = {"A": (5, 50), "B": (25, 20), "C": (25, 80), "D": (45, 45), "E": (50, 10),
"F": (55, 85), "G": (70, 35), "H": (75, 65), "I": (95, 20), "J": (95, 75)}
roads = "AB AC AD BD BE CD CF DG DH EG EI FH FJ GI GH HJ IJ".split()
arcs = []
for u, v in roads:
km = math.ceil(math.dist(towns[u], towns[v]))
if (u, v) == ("D", "G"):
arcs.append(("D", "G", km - 40)) # refund: one-way, cost -13
else:
arcs += [(u, v, km), (v, u, km)]
names = sorted(towns)
INF = float("inf")
def bellman_ford(s):
d = {v: INF for v in names}; d[s] = 0
relax = 0
for _ in range(len(names) - 1):
changed = False
for u, v, w in arcs:
relax += 1
if d[u] + w < d[v]:
d[v] = d[u] + w; changed = True
if not changed:
break
assert not any(d[u] + w < d[v] for u, v, w in arcs), "negative cycle"
return d, relax
def floyd_warshall():
D = {u: {v: 0 if u == v else INF for v in names} for u in names}
for u, v, w in arcs:
D[u][v] = min(D[u][v], w)
steps = 0
for k in names:
for i in names:
for j in names:
steps += 1
if D[i][k] + D[k][j] < D[i][j]:
D[i][j] = D[i][k] + D[k][j]
assert all(D[v][v] == 0 for v in names)
return D, steps
def dijkstra(s): # used anyway, to show what goes wrong
d, done, pq = {s: 0}, set(), [(0, s)]
while pq:
du, u = heapq.heappop(pq)
if u in done: continue
done.add(u)
for x, v, w in arcs:
if x == u and v not in done and (v not in d or du + w < d[v]):
d[v] = du + w; heapq.heappush(pq, (d[v], v))
return d
bf, relax = bellman_ford("A")
D, steps = floyd_warshall()
dj = dijkstra("A")
print("costs from A, Bellman-Ford:", bf)
print("row A of Floyd-Warshall agrees:", D["A"] == bf)
print("Dijkstra (unsafe here) differs at:", {v: (dj[v], bf[v]) for v in names if dj[v] != bf[v]} or "nowhere")
print(f"work: Bellman-Ford from A {relax} relaxations; Floyd-Warshall, all {len(names) ** 2} pairs, {steps} steps")
print("cheapest trip from E to C:", D["E"]["C"], " from C to E:", D["C"]["E"])costs from A, Bellman-Ford: {'A': 0, 'B': 37, 'C': 37, 'D': 41, 'E': 61, 'F': 68, 'G': 28, 'H': 59, 'I': 58, 'J': 82}
row A of Floyd-Warshall agrees: True
Dijkstra (unsafe here) differs at: nowhere
work: Bellman-Ford from A 66 relaxations; Floyd-Warshall, all 100 pairs, 1000 steps
cheapest trip from E to C: 101 from C to E: 61
The refund makes every trip through cheaper ( to now costs 82 instead of 101), and the table is no longer symmetric: and cost different amounts, because the refund only applies eastbound. On this graph Dijkstra happens to get every cost from right, but that is luck: its correctness proof needs non-negative weights, and Bellman-Ford, Floyd-Warshall or Johnson are the safe choices.
Step 5: The core in C++
The C++ version runs Dijkstra and A* for one query with std::priority_queue, counts settled towns, and prints the route.
#include <cmath>
#include <cstdio>
#include <functional>
#include <queue>
#include <string>
#include <utility>
#include <vector>
int main() {
const std::string names = "ABCDEFGHIJ";
const double x[] = {5, 25, 25, 45, 50, 55, 70, 75, 95, 95}, y[] = {50, 20, 80, 45, 10, 85, 35, 65, 20, 75};
const char* roads[] = {"AB", "AC", "AD", "BD", "BE", "CD", "CF", "DG", "DH", "EG", "EI", "FH", "FJ", "GI", "GH", "HJ", "IJ"};
const int n = 10;
auto dist = [&](int a, int b) { return std::hypot(x[a] - x[b], y[a] - y[b]); };
std::vector<std::vector<std::pair<int, int>>> adj(n);
for (const char* r : roads) {
int u = r[0] - 'A', v = r[1] - 'A', km = static_cast<int>(std::ceil(dist(u, v)));
adj[u].push_back({v, km}); adj[v].push_back({u, km});
}
auto search = [&](int s, int t, bool use_h) {
auto h = [&](int v) { return use_h ? dist(v, t) : 0.0; };
std::vector<int> d(n, 1 << 30), parent(n, -1);
std::vector<bool> done(n, false);
using Item = std::pair<double, int>;
std::priority_queue<Item, std::vector<Item>, std::greater<Item>> pq;
d[s] = 0;
pq.push({h(s), s});
int settled = 0;
while (!pq.empty()) {
int u = pq.top().second; pq.pop();
if (done[u]) continue;
done[u] = true; ++settled;
if (u == t) break;
for (auto [v, w] : adj[u])
if (d[u] + w < d[v]) { d[v] = d[u] + w; parent[v] = u; pq.push({d[v] + h(v), v}); }
}
std::string path;
for (int v = t; v != -1; v = parent[v]) path = names[v] + path;
std::printf("%-8s %c -> %c: %d km via %s, %d towns settled\n", use_h ? "A*" : "Dijkstra",
names[s], names[t], d[t], path.c_str(), settled);
};
search(0, 9, false);
search(0, 9, true);
}Dijkstra A -> J: 101 km via ADHJ, 10 towns settled
A* A -> J: 101 km via ADHJ, 4 towns settled
Ideas to extend the planner
- Turn penalties and time of day: make each vertex a (town, arrival direction) pair, or each edge weight a function of the departure time; Dijkstra still works if waiting never helps (the FIFO property).
- Bidirectional search: run Dijkstra from both ends and stop when the two settled sets meet; it settles roughly two small circles instead of one large one.
- Alternative routes: after finding the best route, penalize its edges and search again, or compute the shortest simple paths (Yen's algorithm).
- Larger maps: generate a grid-like map of thousands of towns with a seeded generator and compare the counts of Step 2 and Step 3 as the map grows.
Test yourself
Why may Dijkstra stop as soon as the destination is settled?
- Because the queue is then empty
- Because a settled vertex's distance is final, so later work cannot change it
- Because A* says so
- It may not
Why is A* with the straight-line heuristic guaranteed to find a shortest route on this map?
- Because the map is planar
- Because no road is shorter than the straight line, so the reweighted edges are non-negative and A* is Dijkstra on them
- Because it settles every town
- It is not guaranteed
A road with a refund has negative cost. Which algorithms remain safe for single-source queries?
- Dijkstra and A*
- Bellman-Ford (and Johnson's reweighting followed by Dijkstra)
- BFS
- None