Travelling salesperson
Level 3 of 3
Also called The travelling salesman problem and Exhaustive search in Steinhaus-Johnson-Trotter order.
how it works
The idea on a ring of 4 places, as the watch page runs it.
A salesperson leaves the start, visits every other place once and comes back. Each leg goes the shortest way along the roads, through other places where that is shorter; passing through a place is not a visit. The method tries every order of the other places. It makes each order from the one before by swapping two neighbouring stops, picked by a fixed rule that meets every order exactly once: Steinhaus, Johnson and Trotter's. Trying every order is called exhaustive search. For each order the method adds up the legs and keeps the shortest trip. This page counts legs added up.
| from | A | B | E | F |
|---|---|---|---|---|
| A | 0 | 4 | 2 | 7 |
| B | 4 | 0 | 6 | 3 |
| E | 2 | 6 | 0 | 5 |
| F | 7 | 3 | 5 | 0 |
| step | swap | trip | legs add up to |
|---|---|---|---|
| 2 | none, the first order | A B E F | 4 + 6 + 5 + 7 = 22 |
| 3 | F and E | A B F E | 4 + 3 + 5 + 2 = 14 |
| 4 | F and B | A F B E | 7 + 3 + 6 + 2 = 18 |
| 5 | E and B | A F E B | 7 + 5 + 6 + 4 = 22 |
| 6 | E and F | A E F B | 2 + 5 + 3 + 4 = 14 |
| 7 | B and F | A E B F | 2 + 6 + 3 + 7 = 18 |
step 1 of 8
Find the shortest round trip that leaves A, visits the other 3 places once each and comes back. Each leg takes the shortest way along the roads, through other places where that is shorter than a road of its own. There are 6 orders to visit them in.
what it remembers to know where it is
- trip drawn
- not yet
- its length
- not yet
- shortest trip kept
- not yet
- shortest length
- not yet
Where it says not yet, nothing is held there at that moment.
step 2 of 8
Try the first order: A B E F, then back to A. Its legs add up to 22. Nothing is kept yet, so keep this trip.
what it remembers to know where it is
- trip drawn
- A B E F
- its length
- 22
- shortest trip kept
- A B E F
- shortest length
- 22
step 3 of 8
Swap F and E: A B F E, then back to A, adds up to 14, shorter than the 22 of the trip kept. Keep this one instead.
what it remembers to know where it is
- trip drawn
- A B F E
- its length
- 14
- shortest trip kept
- A B F E
- shortest length
- 14
step 4 of 8
Swap F and B: A F B E, then back to A, adds up to 18, which is not shorter than the 14 of the trip kept. Keep that one.
what it remembers to know where it is
- trip drawn
- A F B E
- its length
- 18
- shortest trip kept
- A B F E
- shortest length
- 14
step 5 of 8
Swap E and B: A F E B, then back to A, adds up to 22, which is not shorter than the 14 of the trip kept. Keep that one.
what it remembers to know where it is
- trip drawn
- A F E B
- its length
- 22
- shortest trip kept
- A B F E
- shortest length
- 14
step 6 of 8
Swap E and F: A E F B, then back to A, adds up to 14, which is not shorter than the 14 of the trip kept. Keep that one.
what it remembers to know where it is
- trip drawn
- A E F B
- its length
- 14
- shortest trip kept
- A B F E
- shortest length
- 14
step 7 of 8
Swap B and F: A E B F, then back to A, adds up to 18, which is not shorter than the 14 of the trip kept. Keep that one.
what it remembers to know where it is
- trip drawn
- A E B F
- its length
- 18
- shortest trip kept
- A B F E
- shortest length
- 14
step 8 of 8
All 6 orders have been tried, and none is shorter than A B F E, then back to A: 14 in all, the shortest a round trip can be.
what it remembers to know where it is
- trip drawn
- A B F E
- its length
- 14
- shortest trip kept
- A B F E
- shortest length
- 14
the steps, in plain words
choose a step to mark the Python, a programming language, that does it
- start at the start; each leg takes the shortest way along the roads, through other places where that is shorterPython lines 9, 12 and 15
- if a place cannot be reached from the start, there is no round tripPython lines 16 and 17
- for each order of the other places, each made from the one before by swapping two neighbouring stops:Python lines 26, 30, 33 and 34
- add up the legs of the round trip in that orderPython lines 19, 21 and 35
- if it is shorter than the shortest so far, keep itPython lines 25, 36 and 37
- no round trip is shorter than the trip keptPython lines 28, 29 and 38
the same in Python
The steps in plain words are what to learn. Python is a programming language, and the code below does the same steps, for those who code. Python numbers the places in a list from 0, not 1: the first number is numbers[0], the second numbers[1], and so on.
def travelling_salesperson(roads, start):
"""The shortest round trip from start that visits every other place once and comes back.
roads is a list of [a, b, length], each road both ways. Each leg takes the shortest way
along the roads. Returns each place's stop number, start 1, or {} if a place is cut off.
"""
places = sorted({p for a, b, _ in roads for p in (a, b)})
far = float("inf")
way = {p: {q: 0 if p == q else far for q in places} for p in places}
for a, b, length in roads:
way[a][b] = way[b][a] = min(way[a][b], length)
for k in places: # the shortest way between every two places, through k or not
for p in places:
for q in places:
way[p][q] = min(way[p][q], way[p][k] + way[k][q])
if any(way[start][p] == far for p in places): # a place cut off: no round trip
return {}
def total(stops): # the legs of the round trip, added up
trip = [start] + stops + [start]
return sum(way[trip[i]][trip[i + 1]] for i in range(len(trip) - 1))
stops = [p for p in places if p != start]
faces = [-1] * len(stops) # each stop faces left at first
best, shortest = list(stops), total(stops)
while True:
movable = [i for i in range(len(stops)) if 0 <= i + faces[i] < len(stops) and stops[i] > stops[i + faces[i]]]
if not movable: # no stop can move: every order has been tried
break
i = max(movable, key=lambda m: stops[m]) # the largest stop that can move swaps with its neighbour
j = i + faces[i]
moved = stops[i]
stops[i], stops[j], faces[i], faces[j] = stops[j], stops[i], faces[j], faces[i]
faces = [-f if s > moved else f for s, f in zip(stops, faces)] # every larger stop turns round
length = total(stops)
if length < shortest: # shorter than the trip kept: keep this one
best, shortest = list(stops), length
return {p: k + 1 for k, p in enumerate([start] + best)}
how it scales
The plot counts the legs the method adds up on a map of places in one piece, measured from 2 places to 12.
Each dotted line up is ten times the one below, and each mark across adds the same number of places. A count that doubled with each place would climb in a straight line here. The legs climb faster: each new place multiplies them by the new number of places, so the points bend upwards. From 6 places to 12, the legs go from 720 to 479,001,600, more than half a million times. Question 2 in section 4 works out why.
legs added up, ten times more at each mark up
, how many places are on the map, the same step more at each mark to the right
- a map of places in one piece, which costs the same whatever its roadssolid where measured by running it; dashed where its formula carries it on to 40
| legs added up | time | |
|---|---|---|
| 13 | 6,227,020,800 | about 6.2 seconds |
| 27 | about | about years |
| 40 | about | about years |
The legs added up are the same on any computer. The times are not: a real computer may be faster or slower than a billion a second.
make these counts yourself
Copy this script and run it with Python 3.12 or later. It counts the same steps as the plot. Where a count depends on a random shuffle, yours will differ a little.
"""Count the travelling salesperson's legs yourself, as the plot on this page does.
Run it with Python 3.12 or later. For each map of 2 to 12 places in a line, it
prints the orders the method tries and the legs it adds up: up to 10 places by
running the swaps, past 10 by multiplying. The counts are the same on any
computer, and on any map in one piece; only the time differs.
"""
def travelling_salesperson(roads, start):
"""The shortest round trip from start that visits every other place once and comes back.
roads is a list of [a, b, length], each road both ways. Each leg takes the shortest way
along the roads. Returns each place's stop number, start 1, or {} if a place is cut off.
"""
places = sorted({p for a, b, _ in roads for p in (a, b)})
far = float("inf")
way = {p: {q: 0 if p == q else far for q in places} for p in places}
for a, b, length in roads:
way[a][b] = way[b][a] = min(way[a][b], length)
for k in places: # the shortest way between every two places, through k or not
for p in places:
for q in places:
way[p][q] = min(way[p][q], way[p][k] + way[k][q])
if any(way[start][p] == far for p in places): # a place cut off: no round trip
return {}
def total(stops): # the legs of the round trip, added up
trip = [start] + stops + [start]
return sum(way[trip[i]][trip[i + 1]] for i in range(len(trip) - 1))
stops = [p for p in places if p != start]
faces = [-1] * len(stops) # each stop faces left at first
best, shortest = list(stops), total(stops)
while True:
movable = [i for i in range(len(stops)) if 0 <= i + faces[i] < len(stops) and stops[i] > stops[i + faces[i]]]
if not movable: # no stop can move: every order has been tried
break
i = max(movable, key=lambda m: stops[m]) # the largest stop that can move swaps with its neighbour
j = i + faces[i]
moved = stops[i]
stops[i], stops[j], faces[i], faces[j] = stops[j], stops[i], faces[j], faces[i]
faces = [-f if s > moved else f for s, f in zip(stops, faces)] # every larger stop turns round
length = total(stops)
if length < shortest: # shorter than the trip kept: keep this one
best, shortest = list(stops), length
return {p: k + 1 for k, p in enumerate([start] + best)}
def orders(roads, start):
"""The orders the method tries. Up to 10 places it runs the swaps and counts the orders;
past 10 it multiplies: a new stop takes each place in each order of the others, so 2
orders of 2 stops make 6 of 3. Trying 39,916,800 orders in Python takes minutes."""
places = {p for a, b, _ in roads for p in (a, b)}
reached, grew = {start}, True
while grew: # the places start can reach
grew = False
for a, b, _ in roads:
if (a in reached) != (b in reached):
reached |= {a, b}
grew = True
if reached != places: # a place cut off: no order is tried
return 0
if len(places) > 10:
made = 1
for k in range(2, len(places)): # 1 stop has 1 order; each next stop multiplies them
made *= k
return made
stops = list(range(len(places) - 1))
faces = [-1] * len(stops)
made = 1
while True: # the page's swaps, nothing added up
movable = [i for i in range(len(stops)) if 0 <= i + faces[i] < len(stops) and stops[i] > stops[i + faces[i]]]
if not movable:
return made
i = max(movable, key=lambda m: stops[m])
j = i + faces[i]
moved = stops[i]
stops[i], stops[j], faces[i], faces[j] = stops[j], stops[i], faces[j], faces[i]
faces = [-f if s > moved else f for s, f in zip(stops, faces)]
made += 1
def count(roads, start):
"""The legs the method adds up: one for each place, in each order tried."""
places = {p for a, b, _ in roads for p in (a, b)}
return orders(roads, start) * len(places)
if __name__ == "__main__":
print(f"{'places':>6} {'orders':>11} {'legs':>12}")
for n in range(2, 13):
names = [f"p{k:02d}" for k in range(1, n + 1)]
roads = [[names[k], names[k + 1], 1] for k in range(n - 1)]
print(f"{n:>6} {orders(roads, names[0]):>11} {count(roads, names[0]):>12}")
best, worst and average
Best, worst and average usually name different inputs of one size. Here every map of places in one piece costs the same, whatever its roads and lengths, as the method tries every order anyway. So the table has one column, under the name worst. A map with a place cut off stops before it tries any order.
A case is one kind of input. A bound says how fast its cost grows as grows.
The counts are in the grid. Here each count is or alone, so its bounds are the count itself.
| worsta map of places in one piece, which costs the same whatever its roads | |
|---|---|
| orders tried | |
| legs added up | |
| how the legs added up grow in each case | |
| tight, | |
| ceiling, | |
| floor, | |
extra memory: the shortest way between every two places, times of them. The trip being tried, and which way each stop moves next, left or right. The trip kept and its length.
Extra memory is the room it needs on top of the input itself, while it runs.
| places | orders | legs |
|---|---|---|
| 2 | 1 | 2 |
| 3 | 2 | 6 |
| 4 | 6 | 24 |
| 5 | 24 | 120 |
| 6 | 120 | 720 |
where the formula comes from
Three questions, each worked line by line. Question 2 is the count the plot draws.
the move: the start stays first
the line:why it is allowed: Every round trip leaves the start and comes back to it, so only the order of the other places changes. For the ring from A, the orders of B, E and F.
the move: count the choices
the line:first stop then then B E F B F E E B F E F B F B E F E B The ring from A: 3 choices for the first stop, each with 2 for the next, each with 1 for the last. 3 times 2 times 1, which is 6 orders. why it is allowed: Any of the other places can come first. Then any place not used yet comes next, and on. For the ring, 3 choices, then 2, then 1.
guess it, thenthe move: the swaps meet each once
the line:order of B and E F steps through it B E B E F, B F E, F B E E B F E B, E F B, E B F The ring's run: F walks across B E, then E B. 2 orders times 3 places is 6 orders, none twice. why it is allowed: The largest stop, the last in the alphabet (F on the ring), steps one place at a time across an order of the others. At each end the others make one swap by the same rule, so they meet each of their own orders once. A map of one place fewer does the same: on 5 places, the ring's 6. So the largest stop stands in every place of every order of the others once, and no order comes twice.
guess it, thenthe move: multiply the choices
the line:why it is allowed: By lines 2 and 3, the method tries every order once, and the choices multiply: for the first stop, one fewer each stop after, down to 1. For the ring, 3 times 2 times 1. At 2 places, just 1.
guess it, thenthe move: name it
the line:why it is allowed: That product is written , read factorial. For the ring, 3! is 6.
guess it, then
try it with a small : at , line 4 gives , which you can work out by hand
the move: legs in each order
the line:why it is allowed: A round trip of places has legs, one from each stop to the next, the last back to the start. By question 1, the method tries orders and adds up legs in each. For the ring, 4 legs in each of 6 orders.
the move: one product
the line:places legs times the row above 6 720 7 5,040 7 times 8 40,320 8 times 9 362,880 9 times 12 479,001,600 Each new place multiplies the legs by the new number of places, faster than any doubling. why it is allowed: times multiplies every whole number from down to 1, which is . For the ring, 4 times 6, which is 24.
guess it, thenthe move: a ceiling
the line:why it is allowed: By line 2, is , so at most .
guess it, thenthe move: read the bound
the line:why it is allowed: By line 3: at most 1 times , at every .
guess it, thenthe move: a floor
the line:why it is allowed: By line 2 again, is , so at least .
guess it, thenthe move: read the bound
the line:why it is allowed: By line 5: at least 1 times , at every .
guess it, thenthe move: both together
the line:why it is allowed: Lines 4 and 6 bound by the same growth, , from above and below.
guess it, then
try it with a small : at , line 1 gives , which you can work out by hand
the move: each trip twice
the line:order its reverse both add up to A B E F A F E B 22 A B F E A E F B 14 A F B E A E B F 18 The ring's 6 orders are 3 round trips, each tried both ways. why it is allowed: Backwards, a trip passes the same legs, each as long both ways, so it adds up the same. From 3 places on, its first and last stops trade places, so it is another order: B E F and F E B. At 2 places, A B A backwards is A B A.
the move: halve the orders
the line:why it is allowed: By question 1 there are orders, and by line 1 each trip is two of them. For the ring, 6 halved, 3. For the nine towns of the books' volume four, chapter 44, 8! halved, 20,160.
guess it, then
try it with a small : at , line 2 gives , which you can work out by hand
count it yourself
The ring of 4 places, step by step. Each order adds 4 legs.
| step | what happens | orders tried | legs added up |
|---|---|---|---|
| 1 | Find the shortest round trip that leaves A, visits the other 3 places once each and comes back. Each leg takes the shortest way along the roads, through other places where that is shorter than a road of its own. There are 6 orders to visit them in. | 0 | 0 |
| 2 | Try the first order: A B E F, then back to A. Its legs add up to 22. Nothing is kept yet, so keep this trip. | 1 | 4 |
| 3 | Swap F and E: A B F E, then back to A, adds up to 14, shorter than the 22 of the trip kept. Keep this one instead. | 2 | 8 |
| 4 | Swap F and B: A F B E, then back to A, adds up to 18, which is not shorter than the 14 of the trip kept. Keep that one. | 3 | 12 |
| 5 | Swap E and B: A F E B, then back to A, adds up to 22, which is not shorter than the 14 of the trip kept. Keep that one. | 4 | 16 |
| 6 | Swap E and F: A E F B, then back to A, adds up to 14, which is not shorter than the 14 of the trip kept. Keep that one. | 5 | 20 |
| 7 | Swap B and F: A E B F, then back to A, adds up to 18, which is not shorter than the 14 of the trip kept. Keep that one. | 6 | 24 |
| 8 | All 6 orders have been tried, and none is shorter than A B F E, then back to A: 14 in all, the shortest a round trip can be. | 6 | 24 |
In all, 24 legs added up. The formula from section 4, , gives at : the same.
where you meet it
The salesperson is one of the best-known hard problems: no exact method known stays fast as maps grow. The books' volume four meets it.
the books' nine towns
A van visits nine towns and comes back. Fixing the start leaves 8! halved, 20,160 different round trips, and trying them all finds the shortest, 155. In the books' words, 'Nine towns is not enough to be hard' (volume four, chapter 44).
source: the books' volume four, chapter 44, What to do when the problem is hard
the biggest solved exactly
By 2006 a team using the program Concorde had found the shortest round trip through 85,900 points of a computer chip's layout, and proved that none is shorter.
source: the University of Waterloo, pla85900 (opens in a new tab)
a faster exact method
In 1962 Michael Held and Richard Karp found an exact method. It keeps, for each group of places and each place it could end at, the shortest way from the start through that group. On the ring, through B and E ending at E: A B E, 10. At 12 places it adds up about 56,000 lengths, against 479,001,600 legs for trying every order.
source: Held and Karp, A Dynamic Programming Approach to Sequencing Problems (opens in a new tab), Journal of the SIAM, 1962
| quick way | trip | legs add up to |
|---|---|---|
| out and back, skipping places seen | A E B F | 18 |
| the nearest place each time | A E F B | 14 |
| A B E F with E F reversed | A B F E | 14 |
what is used instead
Volume four, chapter 44, tries three quick ways that never try every order. Walk the cheapest network joining the places out and back, skipping places already seen. Or go to the nearest place not yet visited. Or reverse a stretch of a trip while that makes it shorter. Only the first promises a fixed bound: never worse than twice the best. Drop one leg of the best trip: the rest joins every place, so the cheapest network is no longer. Out and back is twice the network, and skipping a place never adds length, as each leg is a shortest way.
how it compares
Trying every order is exact and simple, and only small maps allow it. Held and Karp's way is exact and far faster, yet each new place doubles its groups, each old one with or without it, so its work more than doubles. Of section 6's quick ways, only the first promises a fixed bound, twice the best.
| places | trying every order, legs | Held and Karp, sums |
|---|---|---|
| 6 | 720 | about 170 |
| 12 | 479,001,600 | about 56,000 |
| 20 | about 2.4 billion billion | about 45 million |