Hamiltonian Cycles and the Travelling Salesman
A delivery van must visit every customer once and return to the depot along the cheapest route. This is the travelling salesman problem (TSP), probably the most famous NP-hard problem, studied since the 1930s and still the testing ground for exact solvers, heuristics and approximation algorithms. This lesson proves its decision version NP-complete in two steps: vertex cover reduces to the Hamiltonian cycle problem by a gadget construction, and Hamiltonian cycle reduces to TSP almost trivially. It ends with the best known exact algorithm, a dynamic program in , and a proof that general TSP cannot even be approximated.
The problems
A Hamiltonian cycle of an undirected graph is a simple cycle through every vertex. HAM-CYCLE asks whether a graph has one. In the TSP, a complete graph on cities has integer edge costs ; a tour is a Hamiltonian cycle, and its cost is the sum of its edge costs:
Both are in NP: the certificate is the cycle, checked in polynomial time (Verification and the Class NP).
VERTEX-COVER reduces to HAM-CYCLE
Given and , build a graph that has a Hamiltonian cycle exactly when has a vertex cover of size (assume ). The construction uses an edge gadget of 12 vertices for each edge of : two rows of six, and , each row a path, plus four cross edges –, –, – and –. Only the four corners , , , connect to the rest of .
A Hamiltonian cycle of can pass through such a gadget in exactly three ways: enter at and leave at after visiting all 12 vertices (the edge is "covered by alone"), the same from the side, or pass through the two rows separately, once from to and once from to ("covered by both"). Any other route strands a vertex of the gadget.
Then, for every vertex of , chain the -rows of the gadgets of all edges at (in any fixed order) by joining the exit corner of one to the entry corner of the next; this is "'s path". Finally add selector vertices , each joined to the first entry and the last exit of every vertex's path. A Hamiltonian cycle goes from a selector through one chosen vertex path to the next selector, so it selects exactly vertex paths; every gadget must be visited, which is possible exactly when every edge has a selected endpoint. So is Hamiltonian if and only if has a vertex cover of size . has vertices and edges, built in polynomial time, so HAM-CYCLE is NP-complete.
The gadget's "exactly three ways" claim can be checked by computer. The program enumerates every way to cover the 12 gadget vertices with one or two vertex-disjoint paths whose endpoints are corners, which is how a Hamiltonian cycle of can use the gadget, and reports which corners pair up.
from itertools import permutations
U = [("u", i) for i in range(1, 7)]
V = [("v", i) for i in range(1, 7)]
edges = {frozenset(p) for row in (U, V) for p in zip(row, row[1:])}
edges |= {frozenset(p) for p in [(U[2], V[0]), (V[2], U[0]), (U[5], V[3]), (V[5], U[3])]}
corners = {U[0], U[5], V[0], V[5]}
nodes = U + V
adj = {x: [y for y in nodes if frozenset((x, y)) in edges] for x in nodes}
def paths_from(start, allowed):
"""all simple paths from start inside `allowed`, as tuples"""
out, stack = [], [(start,)]
while stack:
p = stack.pop()
out.append(p)
for y in adj[p[-1]]:
if y in allowed and y not in p:
stack.append(p + (y,))
return out
name = lambda c: f"{c[0]}{c[1]}"
seg = lambda p: "-".join(sorted([name(p[0]), name(p[-1])]))
ways = set()
for p in [p for c in sorted(corners) for p in paths_from(c, set(nodes))]:
if p[-1] in corners and p[-1] != p[0]:
if len(p) == 12:
ways.add(("one path", seg(p)))
rest = set(nodes) - set(p)
for c in sorted(corners & rest):
for q in paths_from(c, rest):
if len(q) == len(rest) and q[-1] in corners:
pair = sorted([seg(p), seg(q)])
ways.add(("two paths", " and ".join(pair)))
for kind, w in sorted(ways):
print(f"{kind:9}: {w}")one path : u1-u6
one path : v1-v6
two paths: u1-u6 and v1-v6
The output shows a single path from u1 to u6 or from v1 to v6, or the two rows separately, and nothing else (for example, no route enters at u1 and leaves at v6). That is the gadget property the proof needs.
HAM-CYCLE reduces to TSP
Given , form the complete graph on with cost 0 for the edges of and cost 1 for all other pairs, and set . A tour of cost 0 uses only edges of , so it is a Hamiltonian cycle of , and conversely. The reduction takes time, so TSP is NP-complete.
import random
from itertools import permutations
def ham_cycle(n, E):
return any(all(frozenset((c[i], c[(i + 1) % n])) in E for i in range(n))
for c in ((0,) + p for p in permutations(range(1, n))))
def tsp_at_most(n, cost, k):
return any(sum(cost[c[i]][c[(i + 1) % n]] for i in range(n)) <= k
for c in ((0,) + p for p in permutations(range(1, n))))
def reduce(n, E):
cost = [[0 if frozenset((u, v)) in E else 1 for v in range(n)] for u in range(n)]
return n, cost, 0
rng = random.Random(3)
agree = yes = 0
for trial in range(60):
n = rng.randint(4, 7)
E = {frozenset((u, v)) for u in range(n) for v in range(u + 1, n) if rng.random() < 0.45}
a, b = ham_cycle(n, E), tsp_at_most(*reduce(n, E))
agree += a == b; yes += a
print(f"60 random graphs: HAM-CYCLE and the TSP instance agree on {agree}; {yes} graphs are Hamiltonian")60 random graphs: HAM-CYCLE and the TSP instance agree on 60; 15 graphs are Hamiltonian
TSP cannot be approximated
The same idea shows more. Suppose a polynomial algorithm always found a tour of cost at most times the optimum, for some constant . Give the edges of cost 1 and all other pairs cost . If is Hamiltonian, the optimal tour costs , and the algorithm returns a tour of cost at most , which therefore uses only edges of . If is not Hamiltonian, every tour uses an expensive edge and costs more than . So the approximation algorithm would decide HAM-CYCLE in polynomial time. Unless P = NP, general TSP has no polynomial-time -approximation for any constant . When the costs satisfy the triangle inequality, things change: Coping with NP-Hardness gives a 2-approximation.
Exact TSP by dynamic programming
Brute force examines tours. The Held-Karp dynamic program (1962) does much better. For a set of cities containing the start city 0 and a city , let be the cheapest path that starts at 0, visits exactly the cities of and ends at :
and the optimal tour costs . There are states with work each: time, exponential but far below . No algorithm with running time is known for general TSP.
In C++
Held-Karp in C++ with sets as bitmasks, on 12 cities with fixed pseudo-random coordinates (Manhattan distances), checked against brute force over all tours.
#include <algorithm>
#include <climits>
#include <cstdio>
#include <cstdlib>
#include <vector>
int main() {
const int n = 12;
int x[n], y[n];
unsigned s = 7;
for (int i = 0; i < n; i++) { s = s * 1103515245u + 12345u; x[i] = (s >> 16) % 100; s = s * 1103515245u + 12345u; y[i] = (s >> 16) % 100; }
std::vector<std::vector<int>> c(n, std::vector<int>(n));
for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) c[i][j] = std::abs(x[i] - x[j]) + std::abs(y[i] - y[j]);
const int FULL = 1 << n, INF = INT_MAX / 2;
std::vector<std::vector<int>> D(FULL, std::vector<int>(n, INF));
D[1][0] = 0;
long long states = 0;
for (int S = 1; S < FULL; S += 2) // sets containing city 0
for (int j = 0; j < n; j++) {
if (D[S][j] >= INF || !(S >> j & 1)) continue;
states++;
for (int k = 1; k < n; k++)
if (!(S >> k & 1)) D[S | 1 << k][k] = std::min(D[S | 1 << k][k], D[S][j] + c[j][k]);
}
int best = INF;
for (int j = 1; j < n; j++) best = std::min(best, D[FULL - 1][j] + c[j][0]);
std::vector<int> perm; // brute force: (n - 1)! orders
for (int i = 1; i < n; i++) perm.push_back(i);
int brute = INF;
long long tours = 0;
do {
int cost = c[0][perm[0]] + c[perm.back()][0];
for (int i = 0; i + 1 < (int)perm.size(); i++) cost += c[perm[i]][perm[i + 1]];
brute = std::min(brute, cost);
tours++;
} while (std::next_permutation(perm.begin(), perm.end()));
std::printf("Held-Karp: optimal tour %d, %lld reachable states\n", best, states);
std::printf("brute force: optimal tour %d, %lld orders checked\n", brute, tours);
}Held-Karp: optimal tour 350, 11265 reachable states
brute force: optimal tour 350, 39916800 orders checked
Test yourself
In the reduction from HAM-CYCLE to TSP, which costs are used?
- Cost 1 for edges of and 0 otherwise,
- Cost 0 for edges of and 1 otherwise,
- Random costs
- Cost equal to the degree
In the vertex-cover gadget for edge , what does a Hamiltonian cycle that traverses all 12 vertices in one pass from to correspond to?
- Both and in the cover
- Only in the cover covering this edge
- Neither in the cover
- The edge being deleted
Why can general TSP not be approximated within any constant factor (unless P = NP)?
- Because tours are too long
- Because with costs 1 on edges of and elsewhere, a -approximation would decide HAM-CYCLE
- Because TSP is not in NP
- Because the triangle inequality always holds
What is the running time of the Held-Karp dynamic program?