- Google OR-Tools
- Español – América Latina
- Português – Brasil
- Tiếng Việt
Traveling Salesperson Problem
This section presents an example that shows how to solve the Traveling Salesperson Problem (TSP) for the locations shown on the map below.
The following sections present programs in Python, C++, Java, and C# that solve the TSP using OR-Tools
Create the data
The code below creates the data for the problem.
The distance matrix is an array whose i , j entry is the distance from location i to location j in miles, where the array indices correspond to the locations in the following order:
The data also includes:
- The number of vehicles in the problem, which is 1 because this is a TSP. (For a vehicle routing problem (VRP), the number of vehicles can be greater than 1.)
- The depot : the start and end location for the route. In this case, the depot is 0, which corresponds to New York.
Other ways to create the distance matrix
In this example, the distance matrix is explicitly defined in the program. It's also possible to use a function to calculate distances between locations: for example, the Euclidean formula for the distance between points in the plane. However, it's still more efficient to pre-compute all the distances between locations and store them in a matrix, rather than compute them at run time. See Example: drilling a circuit board for an example that creates the distance matrix this way.
Another alternative is to use the Google Maps Distance Matrix API to dynamically create a distance (or travel time) matrix for a routing problem.
Create the routing model
The following code in the main section of the programs creates the index manager ( manager ) and the routing model ( routing ). The method manager.IndexToNode converts the solver's internal indices (which you can safely ignore) to the numbers for locations. Location numbers correspond to the indices for the distance matrix.
The inputs to RoutingIndexManager are:
- The number of rows of the distance matrix, which is the number of locations (including the depot).
- The number of vehicles in the problem.
- The node corresponding to the depot.
Create the distance callback
To use the routing solver, you need to create a distance (or transit) callback : a function that takes any pair of locations and returns the distance between them. The easiest way to do this is using the distance matrix.
The following function creates the callback and registers it with the solver as transit_callback_index .
The callback accepts two indices, from_index and to_index , and returns the corresponding entry of the distance matrix.
Set the cost of travel
The arc cost evaluator tells the solver how to calculate the cost of travel between any two locations — in other words, the cost of the edge (or arc) joining them in the graph for the problem. The following code sets the arc cost evaluator.
In this example, the arc cost evaluator is the transit_callback_index , which is the solver's internal reference to the distance callback. This means that the cost of travel between any two locations is just the distance between them. However, in general the costs can involve other factors as well.
You can also define multiple arc cost evaluators that depend on which vehicle is traveling between locations, using the method routing.SetArcCostEvaluatorOfVehicle() . For example, if the vehicles have different speeds, you could define the cost of travel between locations to be the distance divided by the vehicle's speed — in other words, the travel time.
Set search parameters
The following code sets the default search parameters and a heuristic method for finding the first solution:
The code sets the first solution strategy to PATH_CHEAPEST_ARC , which creates an initial route for the solver by repeatedly adding edges with the least weight that don't lead to a previously visited node (other than the depot). For other options, see First solution strategy .
Add the solution printer
The function that displays the solution returned by the solver is shown below. The function extracts the route from the solution and prints it to the console.
The function displays the optimal route and its distance, which is given by ObjectiveValue() .
Solve and print the solution
Finally, you can call the solver and print the solution:
This returns the solution and displays the optimal route.
Run the programs
When you run the programs, they display the following output.
In this example, there's only one route because it's a TSP. But in more general vehicle routing problems, the solution contains multiple routes.
Save routes to a list or array
As an alternative to printing the solution directly, you can save the route (or routes, for a VRP) to a list or array. This has the advantage of making the routes available in case you want to do something with them later. For example, you could run the program several times with different parameters and save the routes in the returned solutions to a file for comparison.
The following functions save the routes in the solution to any VRP (possibly with multiple vehicles) as a list (Python) or an array (C++).
You can use these functions to get the routes in any of the VRP examples in the Routing section.
The following code displays the routes.
For the current example, this code returns the following route:
As an exercise, modify the code above to format the output the same way as the solution printer for the program.
The complete TSP programs are shown below.
Example: drilling a circuit board
The next example involves drilling holes in a circuit board with an automated drill. The problem is to find the shortest route for the drill to take on the board in order to drill all of the required holes. The example is taken from TSPLIB, a library of TSP problems.
Here's scatter chart of the locations for the holes:
The following sections present programs that find a good solution to the circuit board problem, using the solver's default search parameters. After that, we'll show how to find a better solution by changing the search strategy .
The data for the problem consist of 280 points in the plane, shown in the scatter chart above. The program creates the data in an array of ordered pairs corresponding to the points in the plane, as shown below.
Compute the distance matrix
The function below computes the Euclidean distance between any two points in the data and stores it in an array. Because the routing solver works over the integers, the function rounds the computed distances to integers. Rounding doesn't affect the solution in this example, but might in other cases. See Scaling the distance matrix for a way to avoid possible rounding issues.
Add the distance callback
The code that creates the distance callback is almost the same as in the previous example. However, in this case the program calls the function that computes the distance matrix before adding the callback.
The following function prints the solution to the console. To keep the output more compact, the function displays just the indices of the locations in the route.
The main function is essentially the same as the one in the previous example , but also includes a call to the function that creates the distance matrix.
Running the program
The complete programs are shown in the next section . When you run the program, it displays the following route:
Here's a graph of the corresponding route:
The OR-Tools library finds the above tour very quickly: in less than a second on a typical computer. The total length of the above tour is 2790.
Here are the complete programs for the circuit board example.
Changing the search strategy
The routing solver does not always return the optimal solution to a TSP, because routing problems are computationally intractable. For instance, the solution returned in the previous example is not the optimal route.
To find a better solution, you can use a more advanced search strategy, called guided local search , which enables the solver to escape a local minimum — a solution that is shorter than all nearby routes, but which is not the global minimum. After moving away from the local minimum, the solver continues the search.
The examples below show how to set a guided local search for the circuit board example.
For other local search strategies, see Local search options .
The examples above also enable logging for the search. While logging isn't required, it can be useful for debugging.
When you run the program after making the changes shown above, you get the following solution, which is shorter than the solution shown in the previous section .
For more search options, see Routing Options .
The best algorithms can now routinely solve TSP instances with tens of thousands of nodes. (The record at the time of writing is the pla85900 instance in TSPLIB, a VLSI application with 85,900 nodes. For certain instances with millions of nodes, solutions have been found guaranteed to be within 1% of an optimal tour.)
Scaling the distance matrix
Since the routing solver works over the integers, if your distance matrix has non-integer entries, you have to round the distances to integers. If some distances are small, rounding can affect the solution.
To avoid any issue with rounding, you can scale the distance matrix: multiply all entries of the matrix by a large number — say 100. This multiplies the length of any route by a factor of 100, but it doesn't change the solution. The advantage is that now when you round the matrix entries, the rounding amount (which is at most 0.5), is very small compared to the distances, so it won't affect the solution significantly.
If you scale the distance matrix, you also need to change the solution printer to divide the scaled route lengths by the scaling factor, so that it displays the unscaled distances of the routes.
Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License , and code samples are licensed under the Apache 2.0 License . For details, see the Google Developers Site Policies . Java is a registered trademark of Oracle and/or its affiliates.
Last updated 2023-01-16 UTC.
Traveling Salesman Problem
The traveling salesman problem (TSP) asks the question, "Given a list of cities and the distances between each pair of cities, what is the shortest possible route that visits each city and returns to the origin city?".
- The goal of this site is to be an educational resource to help visualize, learn, and develop different algorithms for the traveling salesman problem in a way that's easily accessible
- As you apply different algorithms, the current best path is saved and used as input to whatever you run next. (e.g. shortest path first -> branch and bound). The order in which you apply different algorithms to the problem is sometimes referred to the meta-heuristic strategy.
Heuristic algorithms attempt to find a good approximation of the optimal path within a more reasonable amount of time.
Construction - Build a path (e.g. shortest path)
- Shortest Path
- Nearest Insertion
- Convex Hull Insertion*
- Simulated Annealing*
Improvement - Attempt to take an existing constructed path and improve on it
- 2-Opt Inversion
- 2-Opt Reciprcal Exchange*
Exhaustive algorithms will always find the best possible solution by evaluating every possible path. These algorithms are typically significantly more expensive then the heuristic algorithms discussed next. The exhaustive algorithms implemented so far include:
- Random Paths
Depth First Search (Brute Force)
- Branch and Bound (Cost)
- Branch and Bound (Cost, Intersections)*
These are the main tools used to build this site:
- web workers
Pull requests are always welcome! Also, feel free to raise any ideas, suggestions, or bugs as an issue.
This is an exhaustive, brute-force algorithm. It is guaranteed to find the best possible path, however depending on the number of points in the traveling salesman problem it is likely impractical. For example,
- With 10 points there are 181,400 paths to evaluate.
- With 11 points, there are 1,814,000.
- With 12 points there are 19,960,000.
- With 20 points there are 60,820,000,000,000,000, give or take.
- With 25 points there are 310,200,000,000,000,000,000,000, give or take.
This is factorial growth, and it quickly makes the TSP impractical to brute force. That is why heuristics exist to give a good approximation of the best path, but it is very difficult to determine without a doubt what the best path is for a reasonably sized traveling salesman problem.
This is a recursive, depth-first-search algorithm, as follows:
- From the starting point
- For all other points not visited
- If there are no points left return the current cost/path
- Else, go to every remaining point and
- Mark that point as visited
- " recurse " through those paths (go back to 1. )
This is a heuristic, greedy algorithm also known as nearest neighbor. It continually chooses the best looking option from the current state.
- sort the remaining available points based on cost (distance)
- Choose the closest point and go there
- Chosen point is no longer an "available point"
- Continue this way until there are no available points, and then return to the start.
This algorithm is also known as 2-opt, 2-opt mutation, and cross-aversion. The general goal is to find places where the path crosses over itself, and then "undo" that crossing. It repeats until there are no crossings. A characteristic of this algorithm is that afterwards the path is guaranteed to have no crossings.
- While a better path has not been found.
- For each pair of points:
- Reverse the path between the selected points.
- If the new path is cheaper (shorter), keep it and continue searching. Remember that we found a better path.
- If not, revert the path and continue searching.
This is an impractical, albeit exhaustive algorithm. It is here only for demonstration purposes, but will not find a reasonable path for traveling salesman problems above 7 or 8 points.
I consider it exhaustive because if it runs for infinity, eventually it will encounter every possible path.
- From the starting path
- Randomly shuffle the path
- If it's better, keep it
- If not, ditch it and keep going
This is a heuristic construction algorithm. It select a random point, and then figures out where the best place to put it will be.
- First, go to the closest point
- Choose a random point to go to
- Find the cheapest place to add it in the path
- Continue from #3 until there are no available points, and then return to the start.
Two-Opt Reciprocal Exchange
This algorithm is similar to the 2-opt mutation or inversion algorithm, although generally will find a less optimal path. However, the computational cost of calculating new solutions is less intensive.
The big difference with 2-opt mutation is not reversing the path between the 2 points. This algorithm is not always going to find a path that doesn't cross itself.
It could be worthwhile to try this algorithm prior to 2-opt inversion because of the cheaper cost of calculation, but probably not.
- Swap the points in the path. That is, go to point B before point A, continue along the same path, and go to point A where point B was.
Branch and Bound on Cost
This is a recursive algorithm, similar to depth first search, that is guaranteed to find the optimal solution.
The candidate solution space is generated by systematically traversing possible paths, and discarding large subsets of fruitless candidates by comparing the current solution to an upper and lower bound. In this case, the upper bound is the best path found so far.
While evaluating paths, if at any point the current solution is already more expensive (longer) than the best complete path discovered, there is no point continuing.
For example, imagine:
- A -> B -> C -> D -> E -> A was already found with a cost of 100.
- We are evaluating A -> C -> E, which has a cost of 110. There is no point evaluating the remaining solutions.
Instead of continuing to evaluate all of the child solutions from here, we can go down a different path, eliminating candidates not worth evaluating:
- A -> C -> E -> D -> B -> A
- A -> C -> E -> B -> D -> A
Implementation is very similar to depth first search, with the exception that we cut paths that are already longer than the current best.
This is a heuristic construction algorithm. It selects the closest point to the path, and then figures out where the best place to put it will be.
- Choose the point that is nearest to the current path
Branch and Bound (Cost, Intersections)
This is the same as branch and bound on cost, with an additional heuristic added to further minimize the search space.
While traversing paths, if at any point the path intersects (crosses over) itself, than backtrack and try the next way. It's been proven that an optimal path will never contain crossings.
Implementation is almost identical to branch and bound on cost only, with the added heuristic below:
This is a heuristic construction algorithm. It selects the furthest point from the path, and then figures out where the best place to put it will be.
- Choose the point that is furthest from any of the points on the path
This is a heuristic construction algorithm. It starts by building the convex hull , and adding interior points from there. This implmentation uses another heuristic for insertion based on the ratio of the cost of adding the new point to the overall length of the segment, however any insertion algorithm could be applied after building the hull.
There are a number of algorithms to determine the convex hull. This implementation uses the gift wrapping algorithm .
In essence, the steps are:
- Determine the leftmost point
- Continually add the most counterclockwise point until the convex hull is formed
- For each remaining point p, find the segment i => j in the hull that minimizes cost(i -> p) + cost(p -> j) - cost(i -> j)
- Of those, choose p that minimizes cost(i -> p -> j) / cost(i -> j)
- Add p to the path between i and j
- Repeat from #3 until there are no remaining points
Simulated annealing (SA) is a probabilistic technique for approximating the global optimum of a given function. Specifically, it is a metaheuristic to approximate global optimization in a large search space for an optimization problem.
For problems where finding an approximate global optimum is more important than finding a precise local optimum in a fixed amount of time, simulated annealing may be preferable to exact algorithms
Visualize algorithms for the traveling salesman problem. Use the controls below to plot points, choose an algorithm, and control execution. (Hint: try a construction alogorithm followed by an improvement algorithm)
Free Geography Tools
Exploring the world of free tools for GIS, GPS, Google Earth, neogeography, and more.
- Support This Site
Online Traveling Salesman Problem Solver
Wikipedia defines the “Traveling Salesman Problem” this way:
… given a number of cities and the costs of travelling from any city to any other city, what is the least-cost round-trip route that visits each city exactly once and then returns to the starting city?
You can substitute “address” for “city”, making this an intra-urban travel problem. The OptiMap website solves this problem automatically for up to 24 locations (“nodes”). You can enter the nodes by clicking in a Google Maps interface:
You can also enter address nodes individually using the “Add Location By Address” box. Even better, you can add text lists of addresses or coordinates (latitude/longitude) by clicking on the “Bulk add by address or (lat, lng).” link, then copying and pasting the list into the text box that shows up. Latitude/longitude should be in decimal format, one set on each line, separated by commas and surrounded by parentheses, e.g. (35.333, –110.254). You can also specify only walking directions, and avoiding highways. The first node or address entered is always considered to be the starting point.
When you’re done entering nodes, click on “Calculate Fastest Roundtrip” to solve the problem for a round-trip that ends where you started:
You’ll also get a set of Google Maps driving directions for the trip shown in the solution map. By clicking on the “Toggle raw path output” button, you’ll also get a text list of latitude/longitude coordinates in sequence for this route that you could convert into a GPS route:
The “Calculate Fastest A-Z Trip” works in a similar fashion, but for a one-way trip, where the first address/node you entered is taken as the start “A”, and the last address/node is the destination “Z”.
The technical background and source code are available on the OptiMap website , as are instructions on how to use this on your own website.
- Another Google Maps Geocoder/Reverse Geocoder
- Drawing Lines Between Points In Google Maps, Straight And Great Circle
- Coordinate Data From Google Maps
- Easy Google Maps Route Creation With NetKvik
- Compare Point Latitudes And Longitudes With Iso-Longitude-Latitude
2 Responses to “Online Traveling Salesman Problem Solver”
Hi – Here’s an entry with additional info on the traveling salesman: http://technology.slashgeo.org/article.pl?sid=08/01/17/2258255 Cheers and thanks for your useful blog! :-)
- 1 Online Geocoding, Address Verification And Shortest Path Utilities From the USC GIS Research Laboratory | Free Geography Tools Pingback on Feb 10th, 2009 at 6:23 am
Search This Site
- 3D visualization (1)
- Android (5)
- ArcINFO (2)
- AutoCAD (6)
- blogkeeping (6)
- cartography (107)
- coordinate conversion (39)
- crowdsourcing (1)
- demographics (1)
- Garmin (101)
- geocoding (16)
- geology (13)
- geotagging (26)
- global warming (27)
- Google Earth (193)
- Google Maps (114)
- Magellan (12)
- MapWindow (20)
- MicroDEM (33)
- printing (11)
- screencast (4)
- shapefile (71)
- software (10)
- spreadsheet (19)
- topographic maps (45)
- Uncategorized (5)
- Web apps (79)
Copyright And Conditions Of Use
- GIS And Science
- Google Earth Blog
- Google Earth Library
- Google LatLong
- Google Maps Mania
- GPS File Depot
- GPS Tracklog
- Making Maps
- Spatially Adjusted
- Strange Maps
- The Map Room
- Very Spatial
Solving the Traveling Salesman Problem Using Google Maps and Genetic Algorithms
Thought stream, popular tags.
Real-time application of travelling salesman problem using Google Maps API
- Change Username/Password
- Update Address
- Payment Options
- Order History
- View Purchased Documents
- Communications Preferences
- Profession and Education
- Technical Interests
- US & Canada: +1 800 678 4333
- Worldwide: +1 732 981 0060
- Contact & Support
- About IEEE Xplore
- Nondiscrimination Policy
- Privacy & Opting Out of Cookies
A not-for-profit organization, IEEE is the world's largest technical professional organization dedicated to advancing technology for the benefit of humanity. © Copyright 2024 IEEE - All rights reserved. Use of this web site signifies your agreement to the terms and conditions.
Solving the Traveling Salesman Problem Using the Google Maps API
November 6, 2015 brandon comments 0 comment.
The full source code for this problem will not be posted since my intent is not to write work that can easily be used in its entirety as a course project. If you are a course instructor and would like to use this as a demonstration, feel free to contact me with your request through your university email account.
Determining the distance between cities
Using the Google Maps API, the driving distance, driving time, and GPS locations of each city can be determined. To do this, the Google Maps Distance Matrix and the Geocoding APIs was utilized. To request information from these APIs, one simply needs to generate a URL that contains a list of the information desired in a format specified by the API. When the URL is entered into a browser, the resulting webpage contains the desired information. A thorough description urimax 2mg of how to use this API can be determined using the previous links.
An API key is not necessary to use the APIs; however, without a key, your IP address will be limited to 1000 requests per day (multiple users under the same IP will contribute to this limit). With an key, the limit is expanded to 2500 per key.
Now, consider the case where you have a 10 city traveling salesman problem. One could simply create a list of origin and destination cities which would result in a 10×10 matrix. The API could easily handle this request as long as tricor 48 the URL did not exceed the 2000 character limit. However, this is inefficient since the diagonals of this matrix are zeros and the matrix is symmetrical. I.e., the distance from A to B is the same as from B to A (obviously). Therefore, effective programming can be used here to minimize the number of API calls.
Reading the API data with MATLAB
The web read function within MATLAB makes it easy to grab and parse the data returned by the API. This function can grab handle several return formats. For this example, we will use JSON format which the function will automatically recognize and the output variable will be a structure containing the desired data.
To see the JSON file which MATLAB will parse, click here .
To better understand the format of the structure variable DistanceData run the previous code and study the format of the variable in the MATLAB workspace. Then try adding an additional origin city and see how the structure format changes.
For a six city problem, the following distance matrix and city center data was obtained using the API:
Driving Distance Between Cities (miles)
Travel time between cities (hours).
Leave a Reply Cancel reply
Your email address will not be published. Required fields are marked *
Notify me of follow-up comments by email.
Notify me of new posts by email.
Search code, repositories, users, issues, pull requests...
We read every piece of feedback, and take your input very seriously.
Use saved searches to filter your results more quickly.
To see all available qualifiers, see our documentation .
Solving the Traveling Salesman Problem using Google Maps and Genetic Algorithms
- HTML 100.0%