Graph Theory, Step by Step

Free course
Chapter 4 quiz first

First, check Chapter 4

Take the Chapter 4 quiz: 10 questions, and you pass with 7 correct. You can retake it as often as you like.

Every City Once

Chapter 5, lesson 2 of 3

Hamiltonian cycles and the travelling salesman: visit every city exactly once.

Written lesson

9 min read

In 1832 a German handbook for travelling salesmen suggested round trips through Germany and Switzerland. It had no mathematics, only advice: visit as many places as you can without wasting days on the road. In 1856 William Rowan Hamilton turned the idea into a puzzle: travel along the edges of a dodecahedron, visit all twenty corners exactly once, and come back to where you started.

Put a distance on every road and ask for the shortest such round trip, and you have the travelling salesman problem, one of the most studied hard problems in all of mathematics. Ten cities allow 181,440 different round trips; twenty cities allow about sixty thousand trillion. This lesson covers when a tour through every vertex exists, why the salesman is so hard, two fast tricks that find good tours, and how we can prove a tour is the best.

Every vertex once

A Hamiltonian cycle visits every vertex of a graph exactly once and returns to the start. On Hamilton's dodecahedron one exists, through all twenty corners. A London toy maker sold the puzzle as the icosian game: a wooden board with a hole at each corner and numbered pegs to mark the order of the visit.

A Hamiltonian cycle through all twenty corners of the dodecahedron.A Hamiltonian cycle through all twenty corners of the dodecahedron.

Compare it with an Euler circuit from chapter 1, which uses every edge once. For Euler a simple test decides: the graph is connected and every vertex has even degree. For Hamilton, no such test is known.

Some graphs have none:

  • Thomas Kirkman found a polyhedron without one.
  • The Petersen graph from the last lesson has ten vertices and three edges at each, yet a search through every possibility finds no Hamiltonian cycle.
  • In a bipartite graph the cycle must alternate sides, so the two sides need the same size. With two vertices on one side and three on the other, no tour exists.

Graphs with no Hamiltonian cycle.Graphs with no Hamiltonian cycle.

In the other direction, Dirac's theorem (Gabriel Dirac, 1952): if a graph has n ≥ 3 vertices and every vertex is joined to at least n/2 of them, a Hamiltonian cycle is guaranteed.

Even the knight on a chessboard plays this game. In 1759 Leonhard Euler published a knight's tour: 64 squares, each visited exactly once, a Hamiltonian path on the knight's graph.

Euler's knight's tour, 1759.Euler's knight's tour, 1759.

In general, deciding whether a Hamiltonian cycle exists is NP-complete, one of the 21 problems on Richard Karp's famous list of 1972.

The salesman

Now give every pair of cities a distance. The travelling salesman problem (TSP) asks for the shortest Hamiltonian cycle: visit every city once, return home, and travel as little as possible. Karl Menger called it the messenger problem in 1930, since every postman faces it; the name travelling salesman first appeared in print in a 1949 report by Julia Robinson.

Distances need not even be the same both ways. With one-way streets, or a strong wind for a plane, going from A to B can cost more than coming back (the asymmetric TSP).

Counting tours. Our example has ten German cities with straight-line distances. Fix the starting city. There are 9 choices for the next stop, then 8, then 7, and so on, and every tour is counted twice, once in each direction. So n cities give (n − 1)! / 2 tours:

Cities451020
Tours312181,440about 6 × 10¹⁶

A computer checks all 181,440 tours in a blink. The shortest is 1,747 km: Berlin, Hamburg, Hanover, Dortmund, Cologne, Frankfurt, Stuttgart, Munich, Dresden, Leipzig and back to Berlin.

Ten cities, and the best of 181,440 round trips: 1,747 km.Ten cities, and the best of 181,440 round trips: 1,747 km.

Checking a proposed tour is easy: add up ten distances. Finding the best one is the hard part. That gap between checking and finding is the famous P versus NP question, and solving it carries a prize of one million dollars.

The count grows as a factorial. Checking a billion tours every second, twenty cities would take about two years, and twenty-five cities about ten million years.

Two fast tricks

Trick 1: nearest neighbour. Start in Berlin and always drive to the closest city you have not visited yet: Leipzig, then Dresden. Then the nearest unvisited city is far away, Hanover, and the tour zigzags west, down to Munich, and ends with a long drive of 504 km back to Berlin.

Total: 2,051 km, 17% more than the best. Greedy choices early on leave expensive leftovers at the end; on random cities the gap is about 25% on average. The start matters too: beginning in Hamburg, nearest neighbour happens to find the best tour straight away. So a cheap improvement is to try every starting city and keep the shortest.

Nearest neighbour from Berlin: 2,051 km, with three crossings.Nearest neighbour from Berlin: 2,051 km, with three crossings.

Trick 2: 2-opt. The nearest-neighbour route crosses itself three times, and a crossing is always a waste: swap the two crossing roads for the two uncrossed ones, and by the triangle inequality the tour gets shorter.

A 2-opt move removes two roads, reverses the stretch between them, and reconnects:

  1. Remove Dresden-Hanover (313) and Munich-Berlin (504), and add Dresden-Munich (360) and Hanover-Berlin (249): −208 km, down to 1,843 km, with no crossings left.
  2. 2-opt keeps looking for any swap that helps. Remove Berlin-Hanover (249) and Hamburg-Dortmund (284), add Berlin-Hamburg (255) and Hanover-Dortmund (182): −96 km, down to 1,747 km, the best of all 181,440 tours.

After one 2-opt move: 1,843 km, no crossings.After one 2-opt move: 1,843 km, no crossings.

After a second move: 1,747 km, the optimum.After a second move: 1,747 km, the optimum.

Here 2-opt found the optimum. In general it stops at a tour that no single swap can improve, which is usually good but not always the best. Stronger searches swap three or more roads at a time: the Lin-Kernighan method (1973) decides how many on the fly, and its descendants find tours within a fraction of a percent of the best, even for millions of cities.

def tour_length(t, d):
    return sum(d[t[i]][t[(i + 1) % len(t)]] for i in range(len(t)))

def nearest_neighbour(d, start):
    tour, left = [start], set(d) - {start}
    while left:
        nxt = min(left, key=lambda c: d[tour[-1]][c])
        tour.append(nxt)
        left.remove(nxt)
    return tour

def two_opt(t, d):
    improved = True
    while improved:
        improved = False
        for i in range(len(t) - 1):
            for j in range(i + 2, len(t) - (i == 0)):
                a, b, c, e = t[i], t[i + 1], t[j], t[(j + 1) % len(t)]
                if d[a][c] + d[b][e] < d[a][b] + d[c][e]:
                    t[i + 1:j + 1] = reversed(t[i + 1:j + 1])  # reverse the stretch
                    improved = True
    return t

names = ["Berlin", "Hamburg", "Hanover", "Dortmund", "Cologne",
         "Frankfurt", "Stuttgart", "Munich", "Leipzig", "Dresden"]
km = [[0, 255, 249, 421, 477, 424, 512, 504, 149, 165],
      [255, 0, 132, 284, 356, 393, 534, 612, 294, 377],
      [249, 132, 0, 182, 249, 262, 402, 489, 215, 313],
      [421, 284, 182, 0, 73, 178, 328, 477, 341, 439],
      [477, 356, 249, 73, 0, 153, 288, 456, 380, 474],
      [424, 393, 262, 178, 153, 0, 153, 304, 294, 372],
      [512, 534, 402, 328, 288, 153, 0, 190, 365, 413],
      [504, 612, 489, 477, 456, 304, 190, 0, 361, 360],
      [149, 294, 215, 341, 380, 294, 365, 361, 0, 100],
      [165, 377, 313, 439, 474, 372, 413, 360, 100, 0]]
d = {a: {b: km[i][j] for j, b in enumerate(names)} for i, a in enumerate(names)}
nn = nearest_neighbour(d, "Berlin")
tour_length(nn, d)  # 2051
tour_length(two_opt(nn, d), d)  # 1747

How good is good?

Without checking every tour, how can we know a tour is good? We need a lower bound: a number no tour can beat.

The spanning tree bound. Take any tour and delete one road. What remains connects every city without a loop: a spanning tree. So every tour is longer than the minimum spanning tree from chapter 4. For our cities the MST is 1,347 km, so no tour can be shorter; the best tour, 1,747 km, is within 30% of that bound.

The minimum spanning tree: 1,347 km, a floor under every tour.The minimum spanning tree: 1,347 km, a floor under every tour.

The same tree also builds tours with a guarantee. In 1976 Nicos Christofides combined it with a matching to stay within 1.5 times the best (for distances that obey the triangle inequality). That guarantee stood for more than forty years; in 2020 it was finally beaten, by less than one part in 10³⁶.

Exact methods are smarter than trying everything. The Held-Karp algorithm (1962) stores best[S][c]: the cheapest way to start at home, visit exactly the set S of cities, and end at c. It works because the best way to visit a set and end at a given city does not depend on the order used earlier, so each subset is solved once and reused. For n cities it takes about n² · 2ⁿ steps: for twenty cities, about 420 million, instead of 6 × 10¹⁶ tours.

from itertools import combinations

def held_karp(d, cities):
    home, rest = cities[0], cities[1:]
    best = {(frozenset([c]), c): d[home][c] for c in rest}
    for size in range(2, len(rest) + 1):
        for subset in combinations(rest, size):
            s = frozenset(subset)
            for c in subset:
                best[(s, c)] = min(best[(s - {c}, p)] + d[p][c] for p in subset if p != c)
    full = frozenset(rest)
    return min(best[(full, c)] + d[c][home] for c in rest)

held_karp(d, names)  # 1747
held_karp(d, ["Berlin", "Hamburg", "Hanover", "Leipzig", "Dresden", "Munich"])  # 1485

Records. In 1954 George Dantzig, Ray Fulkerson and Selmer Johnson solved a tour of 49 American cities by pushing a lower bound up until it met their tour. That idea still powers the record breakers: in 2006 the Concorde solver proved the best tour through 85,900 points, a layout from a computer chip, using more than 136 years of computer time.

From 49 cities in 1954 to 85,900 points in 2006.From 49 cities in 1954 to 85,900 points in 2006.

In the world

  • Circuit boards. Those 85,900 points were real work: machines that drill thousands of holes in a board must visit every hole once, and a shorter tour means more boards every hour.
  • Deliveries. Vans, school buses and warehouse pickers solve the salesman every day, usually with extra rules, like time windows and several vehicles.
  • Telescopes. Swinging a big telescope from one star to the next takes time, so the night's observations are ordered as a short tour across the sky.
  • Biology. Putting fragments of DNA back in the right order is a search for a path that visits every fragment once.

Key ideas

  • A Hamiltonian cycle visits every vertex once. Unlike Euler circuits, no simple test decides whether one exists: the question is NP-complete.
  • The travelling salesman asks for the shortest one, and the number of tours, (n − 1)!/2, grows as a factorial.
  • Nearest neighbour builds a tour fast; 2-opt removes crossings and wasted roads.
  • Lower bounds, like the minimum spanning tree, tell us how far from the best a tour can possibly be. Held-Karp solves small cases exactly in about n² · 2ⁿ steps.

Check yourself

1. How many different round trips are there through 7 cities?

2. A complete bipartite graph has 4 vertices on each side. Does it have a Hamiltonian cycle?

3. A tour of 12 cities measures 900 km, and the minimum spanning tree of those cities is 800 km. At most how much shorter can the best tour be than yours?

Practice on the platform

The travelling salesperson guide explains the explosion, the exact methods and the heuristics. In the TSP visualizer, import six of our cities (Berlin, Hamburg, Hanover, Leipzig, Dresden and Munich) with their distances and run the exact Held-Karp solver: it returns the shortest round trip through all six, 1,485 km, exactly the tour our own search found.

Up next

Course content

0 of 20 watched

Chapter 1Graph Theory Foundations

Chapter 2Exploring a GraphChapter 1 quiz first

Chapter 3Shortest PathsChapter 2 quiz first

Chapter 4Connecting CheaplyChapter 3 quiz first

Chapter 5Hard ProblemsChapter 4 quiz first

Chapter 6Network FlowsChapter 5 quiz first