The Traveling Salesman
The Traveling Salesman Problem (TSP): given a list of cities and the distance between every pair, find the shortest round trip that visits each city exactly once and returns to the start.
It sounds simple, and for 5 cities it is. But TSP is NP-hard: no one knows an algorithm that solves every instance in polynomial time, and most computer scientists believe none exists. It appears in delivery routing, drilling holes in circuit boards, and DNA sequencing.
Our cities
Five depots with distances in kilometres (the table is symmetric):
| A | B | C | D | E | |
|---|---|---|---|---|---|
| A | 0 | 12 | 10 | 19 | 8 |
| B | 12 | 0 | 3 | 7 | 2 |
| C | 10 | 3 | 0 | 6 | 20 |
| D | 19 | 7 | 6 | 0 | 4 |
| E | 8 | 2 | 20 | 4 | 0 |
Brute force: try every tour
Fix the start city A and try every order of the other cities. With n cities there are (n - 1)! orders (or half of that, since each tour can be driven in two directions).
from itertools import permutations
cities = "ABCDE"
D = {
"A": {"A": 0, "B": 12, "C": 10, "D": 19, "E": 8},
"B": {"A": 12, "B": 0, "C": 3, "D": 7, "E": 2},
"C": {"A": 10, "B": 3, "C": 0, "D": 6, "E": 20},
"D": {"A": 19, "B": 7, "C": 6, "D": 0, "E": 4},
"E": {"A": 8, "B": 2, "C": 20, "D": 4, "E": 0},
}
def tour_length(tour):
return sum(D[a][b] for a, b in zip(tour, tour[1:] + tour[:1]))
best, checked = None, 0
for rest in permutations(cities[1:]):
tour = ("A",) + rest
checked += 1
if best is None or tour_length(tour) < tour_length(best):
best = tour
print("tours checked:", checked)
print("best:", " -> ".join(best + ("A",)), "=", tour_length(best), "km")tours checked: 24
best: A -> C -> B -> D -> E -> A = 32 km
24 tours is nothing, but the count grows factorially:
import math
for n in [5, 10, 15, 20, 25]:
tours = math.factorial(n - 1) // 2
seconds = tours / 1e9 # a billion tours per second
years = seconds / (3600 * 24 * 365)
print(f"{n:>2} cities: {tours:>28,} tours ~{years:.3g} years") 5 cities: 12 tours ~3.81e-16 years
10 cities: 181,440 tours ~5.75e-12 years
15 cities: 43,589,145,600 tours ~1.38e-06 years
20 cities: 60,822,550,204,416,000 tours ~1.93 years
25 cities: 310,224,200,866,619,719,680,000 tours ~9.84e+06 years
Greedy: nearest neighbour
A heuristic gives a good (not necessarily best) answer quickly. The nearest-neighbour rule: from the current city, always drive to the closest unvisited city.
D = {
"A": {"B": 12, "C": 10, "D": 19, "E": 8},
"B": {"A": 12, "C": 3, "D": 7, "E": 2},
"C": {"A": 10, "B": 3, "D": 6, "E": 20},
"D": {"A": 19, "B": 7, "C": 6, "E": 4},
"E": {"A": 8, "B": 2, "C": 20, "D": 4},
}
def nearest_neighbour(start):
tour, current = [start], start
while len(tour) < len(D):
nxt = min((c for c in D[current] if c not in tour), key=lambda c: D[current][c])
print(f" at {current}: nearest unvisited is {nxt} ({D[current][nxt]} km)")
tour.append(nxt)
current = nxt
return tour
tour = nearest_neighbour("A")
length = sum(D[a][b] for a, b in zip(tour, tour[1:] + tour[:1]))
print(" -> ".join(tour + ["A"]), "=", length, "km") at A: nearest unvisited is E (8 km)
at E: nearest unvisited is B (2 km)
at B: nearest unvisited is C (3 km)
at C: nearest unvisited is D (6 km)
A -> E -> B -> C -> D -> A = 38 km
Nearest neighbour runs in O(n²) but walks into a trap here: after A → E → B → C → D, it has to drive the long 19 km road home. The greedy choice early on (the short hop A → E) forces a bad choice at the end.
Improving a tour: 2-opt
2-opt is a simple local search: take two edges of the tour, and if reversing the segment between them makes the tour shorter, do it. Repeat until no reversal helps.
D = {
"A": {"A": 0, "B": 12, "C": 10, "D": 19, "E": 8},
"B": {"A": 12, "B": 0, "C": 3, "D": 7, "E": 2},
"C": {"A": 10, "B": 3, "C": 0, "D": 6, "E": 20},
"D": {"A": 19, "B": 7, "C": 6, "D": 0, "E": 4},
"E": {"A": 8, "B": 2, "C": 20, "D": 4, "E": 0},
}
def length(tour):
return sum(D[a][b] for a, b in zip(tour, tour[1:] + tour[:1]))
def two_opt(tour):
improved = True
while improved:
improved = False
for i in range(1, len(tour) - 1):
for j in range(i + 1, len(tour)):
candidate = tour[:i] + tour[i:j + 1][::-1] + tour[j + 1:]
if length(candidate) < length(tour):
print(f"reverse {''.join(tour[i:j + 1])}: {length(tour)} -> {length(candidate)} km")
tour, improved = candidate, True
return tour
tour = two_opt(["A", "E", "B", "C", "D"])
print(" -> ".join(tour + ["A"]), "=", length(tour), "km")reverse BCD: 38 -> 33 km
reverse CB: 33 -> 32 km
A -> E -> D -> B -> C -> A = 32 km
Here 2-opt repairs the greedy tour all the way to the optimum. On large instances it typically gets within about 5% of the best tour.
Exact but smarter: dynamic programming
The Held-Karp algorithm uses dynamic programming over subsets: best[S][c] = shortest path that starts at A, visits exactly the cities in set S, and ends at c. It takes O(n² · 2ⁿ) time: still exponential, but far better than n!. For n = 20 that is about 4 × 10⁸ basic steps, compared with about 6 × 10¹⁶ tours for brute force. You'll see the DP technique in the next lessons.
Summary
| Approach | Time | Result |
|---|---|---|
| Brute force | O(n!) |
optimal, only for tiny n |
| Held-Karp DP | O(n² 2ⁿ) |
optimal, up to ~25 cities |
| Nearest neighbour | O(n²) |
fast, often 15–25% too long |
| 2-opt and friends | iterations of O(n²) |
usually within a few percent |
Test yourself
How many different round trips through 6 cities start at a fixed city (counting both directions)?
- 6
- 36
- 120
- 720
What is a heuristic?
- An algorithm that is always optimal
- A fast method that usually gives a good, but not guaranteed best, answer
- A sorting method
- A proof technique
Why did nearest neighbour give a poor tour in the lesson?
- It visited a city twice
- Its early greedy choices forced a long final edge back to the start
- It ignored the distance table
- It sorted the cities