TExcelTAD
Home › Selected Topics: FFT, Strings, Parallelism & NP-Completeness › Hamiltonian Cycles and the Travelling Salesman

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 O(n22n)O(n^2 2^n), 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 nn cities has integer edge costs c(u,v)c(u, v); a tour is a Hamiltonian cycle, and its cost is the sum of its edge costs:

TSP={⟨G,c,k⟩:G has a tour of cost at most k}.\text{TSP} = \{ \langle G, c, k \rangle : G \text{ has a tour of cost at most } k \}.

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 G=(V,E)G = (V, E) and kk, build a graph G′G' that has a Hamiltonian cycle exactly when GG has a vertex cover of size kk (assume k≤∣V∣k \le \lvert V \rvert). The construction uses an edge gadget of 12 vertices for each edge (u,v)(u, v) of GG: two rows of six, [u,v,1..6][u, v, 1..6] and [v,u,1..6][v, u, 1..6], each row a path, plus four cross edges [u,v,3][u, v, 3]–[v,u,1][v, u, 1], [v,u,3][v, u, 3]–[u,v,1][u, v, 1], [u,v,6][u, v, 6]–[v,u,4][v, u, 4] and [v,u,6][v, u, 6]–[u,v,4][u, v, 4]. Only the four corners [u,v,1][u, v, 1], [u,v,6][u, v, 6], [v,u,1][v, u, 1], [v,u,6][v, u, 6] connect to the rest of G′G'.

A Hamiltonian cycle of G′G' can pass through such a gadget in exactly three ways: enter at [u,v,1][u, v, 1] and leave at [u,v,6][u, v, 6] after visiting all 12 vertices (the edge is "covered by uu alone"), the same from the vv side, or pass through the two rows separately, once from [u,v,1][u, v, 1] to [u,v,6][u, v, 6] and once from [v,u,1][v, u, 1] to [v,u,6][v, u, 6] ("covered by both"). Any other route strands a vertex of the gadget.

Then, for every vertex uu of GG, chain the uu-rows of the gadgets of all edges at uu (in any fixed order) by joining the exit corner of one to the entry corner of the next; this is "uu's path". Finally add kk selector vertices s1,…,sks_1, \ldots, s_k, 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 kk vertex paths; every gadget must be visited, which is possible exactly when every edge has a selected endpoint. So G′G' is Hamiltonian if and only if GG has a vertex cover of size kk. G′G' has 12∣E∣+k12\lvert E \rvert + k vertices and O(∣E∣+k∣V∣)O(\lvert E \rvert + k\lvert V \rvert) 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 G′G' can use the gadget, and reports which corners pair up.

python · try it yourself
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 G=(V,E)G = (V, E), form the complete graph on VV with cost 0 for the edges of GG and cost 1 for all other pairs, and set k=0k = 0. A tour of cost 0 uses only edges of GG, so it is a Hamiltonian cycle of GG, and conversely. The reduction takes O(V2)O(V^2) time, so TSP is NP-complete.

python · try it yourself
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 ρ\rho times the optimum, for some constant ρ≥1\rho \ge 1. Give the edges of GG cost 1 and all other pairs cost ρn+1\rho n + 1. If GG is Hamiltonian, the optimal tour costs nn, and the algorithm returns a tour of cost at most ρn\rho n, which therefore uses only edges of GG. If GG is not Hamiltonian, every tour uses an expensive edge and costs more than ρn\rho n. So the approximation algorithm would decide HAM-CYCLE in polynomial time. Unless P = NP, general TSP has no polynomial-time ρ\rho-approximation for any constant ρ\rho. 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 (n−1)!/2(n - 1)!/2 tours. The Held-Karp dynamic program (1962) does much better. For a set SS of cities containing the start city 0 and a city j∈Sj \in S, let D[S,j]D[S, j] be the cheapest path that starts at 0, visits exactly the cities of SS and ends at jj:

D[{0,j},j]=c(0,j),D[S,j]=min⁡i∈S∖{0,j}(D[S∖{j},i]+c(i,j)),D[\{0, j\}, j] = c(0, j), \qquad D[S, j] = \min_{i \in S \setminus \{0, j\}} \bigl(D[S \setminus \{j\}, i] + c(i, j)\bigr),

and the optimal tour costs min⁡j(D[V,j]+c(j,0))\min_j (D[V, j] + c(j, 0)). There are 2n−1n2^{n-1} n states with O(n)O(n) work each: O(n22n)O(n^2 2^n) time, exponential but far below n!n!. No algorithm with running time O(1.9999n)O(1.9999^n) 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.

cpp · try it yourself
#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?

  1. Cost 1 for edges of GG and 0 otherwise, k=nk = n
  2. Cost 0 for edges of GG and 1 otherwise, k=0k = 0
  3. Random costs
  4. Cost equal to the degree

In the vertex-cover gadget for edge (u,v)(u, v), what does a Hamiltonian cycle that traverses all 12 vertices in one pass from [u,v,1][u, v, 1] to [u,v,6][u, v, 6] correspond to?

  1. Both uu and vv in the cover
  2. Only uu in the cover covering this edge
  3. Neither in the cover
  4. The edge being deleted

Why can general TSP not be approximated within any constant factor ρ\rho (unless P = NP)?

  1. Because tours are too long
  2. Because with costs 1 on edges of GG and ρn+1\rho n + 1 elsewhere, a ρ\rho-approximation would decide HAM-CYCLE
  3. Because TSP is not in NP
  4. Because the triangle inequality always holds

What is the running time of the Held-Karp dynamic program?

  1. O(n!)O(n!)
  2. O(n22n)O(n^2 2^n)
  3. O(n3)O(n^3)
  4. O(2n2)O(2^{n^2})