How to Solve the Traveling Salesperson Problem (TSP) in Mathematica
Problem
This example models the nine-city traveling salesperson problem as an undirected graph whose edge weights are distances. The diagram shows the edges and distances used in the example.
Distance graph:
graph LR 1((1)) ---|10| 2((2)) 1 ---|15| 5((5)) 1 ---|12| 4((4)) 1 ---|20| 3((3)) 2 ---|10| 5 3 ---|10| 4 3 ---|30| 8((8)) 3 ---|20| 7((7)) 3 ---|25| 6((6)) 4 ---|15| 5 4 ---|20| 8 5 ---|18| 9((9)) 5 ---|15| 8 6 ---|5| 7 7 ---|35| 8 8 ---|12| 9
Solution
| |
The second argument {9,9} to SparseArray specifies the array dimensions (9 by 9). The third argument, Infinity, is the default value for unspecified entries. Here that means no direct trip is allowed between city pairs omitted from the list. Each edge is listed in both directions so the distances are symmetric.
| |
FindShortestTour returns a closed tour through the specified cities; its result contains the total distance and the city order. The return edge from the last city to the first is included in the total.
Output
| |
For this distance table, there are two shortest tours of length 137; the reverse of either tour has the same length. The order of an optimal tour displayed may vary with the Mathematica version or search order. As the number of cities grows, the search quickly becomes harder, so consider an appropriate optimization method for large instances.
Official documentation: FindShortestTour and SparseArray.
