Solving the Traveling Salesperson Problem with Mathematica
Problem
電車でこんな広告を見かけました😁📸 pic.twitter.com/iXEgvtXrpL
— 早稲田大学 早水桃子研究室 (@hayamizu_lab) October 11, 2022
Solution
| |
We create a matrix using the SparseArray function. Each element represents the distance between cities at the row and column of that element. For example, the first element {1,2}->10 means the distance between 1 and 2 is 10. The second to last element {9,9} indicates the size of the matrix, and the final element Infinity means the length of paths between unspecified cities is infinite, meaning there is no path.
| |
You can easily solve the traveling salesperson problem with the FindShortestTour function. {1,2,3,4,5,6,7,8,9} represents the city numbers. DistanceFunction->(d[[#1,#2]]&) passes the matrix d which represents the distance between cities.
Output
| |
The output gives the shortest distance and the tour route for it. The shortest distance is 137, and the route is 1→2→5→9→8→7→6→3→4→1. Converting this to ABC order gives A, B, E, I, H, G, F, C, D.
