Traveling salesman problem

Also known as: TSP

On this page 7

The traveling salesman problem (TSP) asks for the shortest closed tour that visits every city exactly once and returns to the starting point, given the pairwise distances or costs between the cities. It is the best-known benchmark of combinatorial optimization, the branch of mathematical optimization that searches a finite but enormous set of discrete configurations.

In artificial intelligence and operations research, the TSP serves as a reference problem for search, heuristics and learned solvers. It is NP-hard, so no known algorithm solves every instance in polynomial time, yet modern exact solvers and heuristics routinely handle instances with tens of thousands of cities to proven or near-proven optimality.

How the traveling salesman problem is formulated

Formally, the TSP is defined on a complete weighted graph with n vertices, where each edge weight is the cost of traveling between two cities. A feasible solution is a Hamiltonian cycle, a cycle that passes through every vertex once, and the objective function is the sum of the edge weights along that cycle.

The number of distinct tours in the symmetric case is (n − 1) factorial divided by 2, which explains why brute-force enumeration fails quickly. Ten cities give 181,440 tours, while 20 cities already give about 6 × 10^16. The standard integer programming formulation by Dantzig, Fulkerson and Johnson uses a binary variable per edge, degree constraints that force two edges at each vertex, and subtour elimination constraints that forbid disconnected small cycles.

The table below lists the main ingredients of that formulation and the role each one plays.

ComponentMathematical formPurpose
Decision variablesx_ij ∈ {0, 1} per edgeMark whether the tour uses an edge
ObjectiveMinimize Σ c_ij x_ijTotal tour length or cost
Degree constraintsTwo edges incident to each vertexEach city entered and left once
Subtour eliminationEdges across every cut ≥ 2Forbid separate small loops
Linear relaxation0 ≤ x_ij ≤ 1Supplies lower bounds for search
Components of the integer programming model

Variants of the TSP

The classic problem has many variants, and the variant determines which algorithms and guarantees apply. The most important distinction is whether distances are symmetric and whether they satisfy the triangle inequality, because approximation guarantees depend on these properties.

VariantDefining propertyTypical application
Symmetric TSPCost from A to B equals B to ARoad distances, drilling paths
Asymmetric TSPCosts differ by directionOne-way streets, setup times
Metric TSPTriangle inequality holdsGeographic routing
Euclidean TSPPoints in the plane, straight-line distancesCircuit board drilling, plotting
TSP with time windowsEach city must be visited in an intervalDeliveries, service calls
Prize-collecting TSPCities may be skipped for a penaltySelective inspections
Common TSP variants and their properties

Adding several vehicles, capacities or depots turns the TSP into the vehicle routing problem, which contains the TSP as a special case and is considerably harder to solve to optimality in practice.

Exact algorithms, heuristics and learned solvers

Solution methods fall into three families: exact algorithms that prove optimality, heuristics and metaheuristics that find good tours quickly without a guarantee, and learned solvers that use neural networks to construct or improve tours. The choice depends on instance size, the time budget and whether a certificate of optimality is required.

  • Dynamic programming (Held-Karp) solves the problem in O(n² 2^n) time, which is practical only up to roughly 25-30 cities.
  • Branch and cut combines branch and bound with cutting planes from the linear relaxation; the Concorde solver uses it to prove optimality for instances with tens of thousands of cities.
  • Christofides-type algorithms guarantee a tour at most 1.5 times the optimum for metric instances; a slightly better bound was proven in 2020.
  • Local search with 2-opt, 3-opt and the Lin-Kernighan heuristic typically reaches tours within 1-2% of optimal; the LKH implementation is a widely used reference.
  • Metaheuristics such as simulated annealing, tabu search, genetic algorithms and ant colony optimization escape local optima at the price of more computation.

The following comparison summarizes how these approaches trade solution quality against running time.

ApproachQuality guaranteePractical scale
Held-Karp dynamic programmingOptimalUp to about 30 cities
Branch and cutOptimal with proofThousands to tens of thousands
Christofides-typeAt most 1.5 × optimum (metric)Very large instances
Lin-Kernighan local searchNone, usually within 1-2%Millions of cities
Neural constructive solversNone, gap grows with sizeMostly up to a few thousand
Solution approaches compared

In machine learning research, the TSP is a standard testbed for neural combinatorial optimization. Pointer networks, graph neural networks and transformer models trained with reinforcement learning can construct tours in one forward pass. Their main value is speed on repeated, similar instances; on large or unusual instances, classical heuristics such as LKH remain more reliable.

Complexity and why the TSP is hard

The decision version of the TSP, which asks whether a tour shorter than a given bound exists, is NP-complete, and the optimization version is NP-hard. In practice this means the worst-case running time of every known exact method grows exponentially with the number of cities, even though many real instances are solved far faster than the worst case suggests.

Approximability also depends on structure. For general costs without the triangle inequality, no constant-factor approximation exists unless P equals NP. The Euclidean TSP admits a polynomial-time approximation scheme, which can reach any fixed accuracy, although these schemes are mainly of theoretical interest.

Practical use and common mistakes

Real applications rarely look like the textbook TSP, so modeling decisions matter as much as the algorithm. The decision table below maps common situations to a sensible strategy.

SituationRecommended approachReason
Fewer than 20 stopsExact dynamic programming or a MIP solverOptimal answer in seconds
Hundreds to thousands of stopsLKH or a branch-and-cut solverNear-optimal or proven tours
Real-time re-planningConstruction heuristic plus 2-optMillisecond response
Many similar daily instancesLearned solver with local search refinementAmortized training cost
Several vehicles or capacitiesVehicle routing solverPlain TSP misses constraints
Choosing a strategy for a routing task
  • Ignoring asymmetry: travel times on real roads often differ by direction, and a symmetric model produces infeasible schedules.
  • Optimizing the wrong objective: minimizing distance when the business cares about time, tolls or lateness yields a misleading tour.
  • Overvaluing learned solvers: reported gaps on random uniform instances rarely transfer to clustered, real-world layouts.
  • Skipping lower bounds: without a bound from the linear relaxation, the quality of a heuristic tour cannot be judged.

The idea in brief

Imagine a courier with a list of addresses. The courier must visit each address once and then return home. The goal is the shortest possible round trip.

With a few stops, you can try every order. With many stops, the number of possible orders explodes. Even fast computers cannot check them all. So people use clever shortcuts that find very good routes quickly, and special methods that can prove a route is the best one.

The traveling salesman problem matters because it is a model for many tasks. Delivery routes, drilling holes in circuit boards and scheduling machines all share the same core puzzle.

A practical scenario

A regional parcel company plans a daily route for one van that serves about 120 stops in a mid-sized city. Planners first build an asymmetric travel-time matrix from road data, because one-way streets and turn restrictions make some trips longer in one direction. A nearest-neighbor construction gives a starting route of 410 minutes.

The team then applies Lin-Kernighan local search, which removes crossings and reorders segments. Within two seconds the route drops to 352 minutes, a reduction of about 14 percent. A lower bound from the linear relaxation shows the tour is within roughly 1 percent of the optimum, so further computation is not worth the time.

When the company later adds a second van and delivery time windows, the planners switch to a vehicle routing solver, since the plain TSP model can no longer express the new constraints.