Lesson 24 · Problem-solving methods

Travelling Salesman Problem

Find the shortest round trip that visits every city once. Brute force checks every order; dynamic programming over visited sets cuts n! down to n²·2ⁿ.

Travelling Salesman Problem concept diagramLeft, five cities: a highlighted route from start s through two cities to the current end city j, with one unvisited city u reached by a dashed candidate edge. Right, logarithmic bars comparing brute-force tours with Held-Karp work for 10, 15 and 20 cities.one DP state: (visited set S, last city j)sjustartcurrent endnot yet visitedvisited set S (blue)work for n cities (log scale)n = 101.8 × 10⁵1.0 × 10⁵n = 154.4 × 10¹⁰7.4 × 10⁶n = 206.1 × 10¹⁶4.2 × 10⁸brute force: (n − 1)!/2 toursHeld–Karp: n²·2ⁿ stepsdp[S][j] = min over i of dp[S − j][i] + d(i, j)
1

The Problem: Cheapest Round Trip

  1. Input – n cities and a cost matrix d[i][j] for every ordered pair.
  2. Tour – a cycle that visits each city exactly once and returns to the start.
  3. Goal – minimise the sum of the edge costs along the tour.

The travelling salesman problem (TSP) gives a set of n cities and the cost of travelling between every pair. The task is to find the cheapest route that visits every city exactly once and returns to the starting city.

In graph terms it asks for a minimum-weight Hamiltonian cycle in a complete weighted graph. The starting city does not matter: a cycle can be rotated to start anywhere, so it is fixed as city 0 without loss of generality.

It comes in two forms. In symmetric TSP the cost from i to j equals the cost from j to i, as with road distances. In asymmetric TSP they can differ, as with one-way streets or flights. The dynamic programming below handles both.

  • Edge cases: one city gives an empty tour of cost 0; two cities give the only tour, there and back
  • A missing road is an infinite cost, and if every tour needs one, no tour exists
2

Brute Force: Checking Every Tour

With the start fixed, a tour is an ordering of the other n − 1 cities, giving (n − 1)! orderings. In the symmetric case each tour and its reverse cost the same, halving that to (n − 1)!/2 distinct tours. Checking one tour costs O(n), so brute force is O(n!).

Factorial growth is faster than any exponential. Ten cities is fine; fifteen is already tens of billions of tours; twenty is out of reach for any computer.

Distinct tours in symmetric TSP, (n − 1)!/2
Cities nDistinct toursHeld–Karp steps n²·2ⁿ
43256
10181,440102,400
1543,589,145,6007,372,800
2060,822,550,204,416,000419,430,400
  • Still useful as a correctness check on small inputs; the code below uses it that way
3

Held–Karp Dynamic Programming

  1. State – dp[S][j]: cheapest path from city 0 through exactly the cities in S, ending at j.
  2. Base – dp[{0}][0] = 0.
  3. Recurrence – dp[S][j] = min over i in S − {j} of dp[S − {j}][i] + d[i][j].
  4. Order – fill sets in increasing size (increasing bitmask works too).
  5. Answer – min over j of dp[all][j] + d[j][0], closing the cycle.

The Held–Karp algorithm (1962) notices that brute force keeps re-solving the same subproblem. The cost of finishing a tour depends only on which cities have been visited and where the path currently is, not on the order they were visited in. Two partial paths with the same set and the same end city can be merged, keeping only the cheaper one.

So define dp[S][j] as the minimum cost of a path that starts at city 0, visits exactly the cities in set S, and ends at city j (with 0 and j both in S). The last step of such a path arrives at j from some city i in S − {j}, and the path up to i is itself optimal for dp[S − {j}][i]. Sets are stored as bitmasks, so S − {j} is mask ^ (1 << j).

There are 2ⁿ sets and n end cities, and each entry tries up to n predecessors: O(n²·2ⁿ) time and O(n·2ⁿ) space. Still exponential, but at n = 20 that is about 4 × 10⁸ steps instead of 6 × 10¹⁶ tours.

  • Exact: it returns the true optimum, not an estimate
  • Practical up to roughly 20–25 cities; memory runs out before time does
Key reference

Terms, operations, and practical uses

Core vocabulary

  • Hamiltonian cycleA cycle that visits every vertex exactly once.
  • BitmaskAn integer whose bits mark which cities are in the visited set.
  • Triangle inequalityd(i, k) ≤ d(i, j) + d(j, k); needed for the approximation guarantees.
  • Held–KarpThe O(n²·2ⁿ) dynamic programming algorithm over (set, end city) states.

Costs

  • Brute force(n − 1)!/2 tours, O(n!) time.
  • Held–Karp timeO(n²·2ⁿ).
  • Held–Karp spaceO(n·2ⁿ): the table, plus the same again for parents.
  • Nearest neighbourO(n²), no guarantee.
Implementation

Code in Python, C++ and Java

from itertools import permutations

INF = float("inf")


def held_karp(dist):
    n = len(dist)
    full = (1 << n) - 1
    # dp[mask][j]: cheapest path that starts at city 0, visits exactly the
    # cities in mask, and ends at city j.
    dp = [[INF] * n for _ in range(1 << n)]
    parent = [[-1] * n for _ in range(1 << n)]
    dp[1][0] = 0

    for mask in range(1, 1 << n):
        if not mask & 1:
            continue  # every path starts at city 0
        for j in range(1, n):
            if not mask & (1 << j):
                continue
            prev = mask ^ (1 << j)
            for i in range(n):
                if prev & (1 << i) and dp[prev][i] + dist[i][j] < dp[mask][j]:
                    dp[mask][j] = dp[prev][i] + dist[i][j]
                    parent[mask][j] = i

    best_end = min(range(1, n), key=lambda j: dp[full][j] + dist[j][0])
    cost = dp[full][best_end] + dist[best_end][0]

    tour, mask, j = [], full, best_end
    while j != -1:
        tour.append(j)
        mask, j = mask ^ (1 << j), parent[mask][j]
    tour.reverse()
    return cost, tour + [0]


def brute_force(dist):
    n = len(dist)
    best = INF
    for order in permutations(range(1, n)):
        route = (0, *order, 0)
        best = min(best, sum(dist[a][b] for a, b in zip(route, route[1:])))
    return best


names = "ABCD"
dist = [
    [0, 10, 15, 20],
    [10, 0, 35, 25],
    [15, 35, 0, 30],
    [20, 25, 30, 0],
]

cost, tour = held_karp(dist)
print("Minimum tour cost:", cost)
print("Tour:", " -> ".join(names[c] for c in tour))
print("Brute force agrees:", brute_force(dist) == cost)
#include <algorithm>
#include <climits>
#include <iostream>
#include <numeric>
#include <vector>

const int INF = INT_MAX / 2;

int heldKarp(const std::vector<std::vector<int>>& dist, std::vector<int>& tour) {
    int n = dist.size(), full = (1 << n) - 1;
    // dp[mask][j]: cheapest path that starts at city 0, visits exactly the
    // cities in mask, and ends at city j.
    std::vector<std::vector<int>> dp(1 << n, std::vector<int>(n, INF));
    std::vector<std::vector<int>> parent(1 << n, std::vector<int>(n, -1));
    dp[1][0] = 0;

    for (int mask = 1; mask < (1 << n); mask++) {
        if (!(mask & 1)) continue;  // every path starts at city 0
        for (int j = 1; j < n; j++) {
            if (!(mask & (1 << j))) continue;
            int prev = mask ^ (1 << j);
            for (int i = 0; i < n; i++) {
                if ((prev & (1 << i)) && dp[prev][i] + dist[i][j] < dp[mask][j]) {
                    dp[mask][j] = dp[prev][i] + dist[i][j];
                    parent[mask][j] = i;
                }
            }
        }
    }

    int bestEnd = 1;
    for (int j = 2; j < n; j++) {
        if (dp[full][j] + dist[j][0] < dp[full][bestEnd] + dist[bestEnd][0]) bestEnd = j;
    }

    tour.clear();
    for (int mask = full, j = bestEnd; j != -1;) {
        tour.push_back(j);
        int p = parent[mask][j];
        mask ^= 1 << j;
        j = p;
    }
    std::reverse(tour.begin(), tour.end());
    tour.push_back(0);
    return dp[full][bestEnd] + dist[bestEnd][0];
}

int bruteForce(const std::vector<std::vector<int>>& dist) {
    std::vector<int> order(dist.size() - 1);
    std::iota(order.begin(), order.end(), 1);
    int best = INF;
    do {
        int cost = dist[0][order.front()] + dist[order.back()][0];
        for (size_t k = 0; k + 1 < order.size(); k++) cost += dist[order[k]][order[k + 1]];
        best = std::min(best, cost);
    } while (std::next_permutation(order.begin(), order.end()));
    return best;
}

int main() {
    const char* names = "ABCD";
    std::vector<std::vector<int>> dist = {
        {0, 10, 15, 20},
        {10, 0, 35, 25},
        {15, 35, 0, 30},
        {20, 25, 30, 0},
    };

    std::vector<int> tour;
    int cost = heldKarp(dist, tour);
    std::cout << "Minimum tour cost: " << cost << '\n';
    std::cout << "Tour: ";
    for (size_t k = 0; k < tour.size(); k++) std::cout << (k ? " -> " : "") << names[tour[k]];
    std::cout << '\n';
    std::cout << "Brute force agrees: " << (bruteForce(dist) == cost ? "True" : "False") << '\n';
}
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class Main {
    static final int INF = Integer.MAX_VALUE / 2;

    static int heldKarp(int[][] dist, List<Integer> tour) {
        int n = dist.length, full = (1 << n) - 1;
        // dp[mask][j]: cheapest path that starts at city 0, visits exactly the
        // cities in mask, and ends at city j.
        int[][] dp = new int[1 << n][n];
        int[][] parent = new int[1 << n][n];
        for (int[] row : dp) Arrays.fill(row, INF);
        for (int[] row : parent) Arrays.fill(row, -1);
        dp[1][0] = 0;

        for (int mask = 1; mask < (1 << n); mask++) {
            if ((mask & 1) == 0) continue; // every path starts at city 0
            for (int j = 1; j < n; j++) {
                if ((mask & (1 << j)) == 0) continue;
                int prev = mask ^ (1 << j);
                for (int i = 0; i < n; i++) {
                    if ((prev & (1 << i)) != 0 && dp[prev][i] + dist[i][j] < dp[mask][j]) {
                        dp[mask][j] = dp[prev][i] + dist[i][j];
                        parent[mask][j] = i;
                    }
                }
            }
        }

        int bestEnd = 1;
        for (int j = 2; j < n; j++) {
            if (dp[full][j] + dist[j][0] < dp[full][bestEnd] + dist[bestEnd][0]) bestEnd = j;
        }

        tour.clear();
        for (int mask = full, j = bestEnd; j != -1; ) {
            tour.add(j);
            int p = parent[mask][j];
            mask ^= 1 << j;
            j = p;
        }
        Collections.reverse(tour);
        tour.add(0);
        return dp[full][bestEnd] + dist[bestEnd][0];
    }

    static int bruteForce(int[][] dist, List<Integer> rest, List<Integer> route) {
        if (rest.isEmpty()) {
            int cost = 0, at = 0;
            for (int c : route) {
                cost += dist[at][c];
                at = c;
            }
            return cost + dist[at][0];
        }
        int best = INF;
        for (int k = 0; k < rest.size(); k++) {
            List<Integer> left = new ArrayList<>(rest);
            int c = left.remove(k);
            route.add(c);
            best = Math.min(best, bruteForce(dist, left, route));
            route.remove(route.size() - 1);
        }
        return best;
    }

    public static void main(String[] args) {
        String names = "ABCD";
        int[][] dist = {
            {0, 10, 15, 20},
            {10, 0, 35, 25},
            {15, 35, 0, 30},
            {20, 25, 30, 0},
        };

        List<Integer> tour = new ArrayList<>();
        int cost = heldKarp(dist, tour);
        System.out.println("Minimum tour cost: " + cost);
        StringBuilder sb = new StringBuilder();
        for (int k = 0; k < tour.size(); k++) sb.append(k > 0 ? " -> " : "").append(names.charAt(tour.get(k)));
        System.out.println("Tour: " + sb);
        int brute = bruteForce(dist, new ArrayList<>(List.of(1, 2, 3)), new ArrayList<>());
        System.out.println("Brute force agrees: " + (brute == cost ? "True" : "False"));
    }
}
Watch it run

Step through it

Running on A–B 10, A–C 15, A–D 20, B–C 35, B–D 25, C–D 30

101520352530ABCDvisited setends Aends Bends Cends D{A}{A,B}{A,C}{A,D}{A,B,C}{A,B,D}{A,C,D}{A,B,C,D}state dp[S][j]: cheapest path from A through set S, ending at j
Step 1

Four cities, every pair connected

Find the cheapest round trip that starts at A, visits B, C and D once each, and returns to A. Brute force would check (4 − 1)!/2 = 3 distinct tours. Held–Karp instead builds the answer from best partial paths, which is what scales.

Output
1 / 16
4

Reconstructing the Optimal Tour

The table gives the minimum cost, not the route. To recover the route, store alongside each entry the predecessor i that achieved the minimum. After finding the best final city j, walk the predecessors back: from (all, j) to (all − {j}, parent), and so on until the path reaches city 0.

  • Costs – A–B 10, A–C 15, A–D 20, B–C 35, B–D 25, C–D 30.
  • Brute force – 3 distinct tours: 80, 95 and 95.
  • Held–Karp – 13 table entries, minimum 80.

In the 4-city example the final entries are dp[ABCD][B] = 70, dp[ABCD][C] = 65 and dp[ABCD][D] = 75. Adding the edge home gives 80, 80 and 95. B and C tie because they are the two directions of the same tour; following the predecessors from B gives A → C → D → B → A = 15 + 30 + 25 + 10 = 80.

  • Keep a parent table the same shape as dp
  • Walk back from the best final city, removing each city from the set
  • Reverse the collected cities to get the tour in order
5

Approximation Algorithms and Heuristics for TSP

Beyond about 25 cities exact DP runs out of memory, and real instances have thousands of cities. They are solved with methods that trade a guarantee for speed.

When costs obey the triangle inequality (d[i][k] ≤ d[i][j] + d[j][k], true for distances), there are approximation algorithms with provable bounds. Without it, no polynomial algorithm can guarantee any constant factor unless P = NP. Branch and bound remains exact but prunes partial tours whose lower bound already exceeds the best tour found.

Common TSP methods
MethodIdeaGuaranteeTime
Nearest neighbouralways go to the closest unvisited citynone; about 25% worse on averageO(n²)
MST 2-approximationwalk a minimum spanning tree, skipping repeats≤ 2 × optimal (metric)O(n² ) or O(E log V)
ChristofidesMST plus a minimum matching on odd-degree vertices≤ 1.5 × optimal (metric)O(n³)
2-opt local searchreverse a segment while it shortens the tournone; strong in practiceper pass O(n²)
Branch and boundprune by lower boundsexactexponential worst case
  • Heuristics like 2-opt, started from a nearest-neighbour tour, are what production solvers build on
6

Why TSP Is NP-Hard

The decision version, is there a tour of cost at most k?, is NP-complete. It is in NP because a proposed tour can be checked in O(n) time. It is NP-hard because the Hamiltonian cycle problem reduces to it: give every existing edge cost 1 and every missing edge cost 2, and a tour of cost n exists exactly when the original graph has a Hamiltonian cycle.

The optimisation version is therefore NP-hard. That is why the exact algorithm above is exponential, and why no one expects a polynomial one: finding it would prove P = NP.

  • Held–Karp's O(n²·2ⁿ) is still the best known worst-case bound for exact TSP