• Awards Season
  • Big Stories
  • Pop Culture
  • Video Games
  • Celebrities

Kate Bove

How Has a Year Without Tourists Impacted the Overtourism Problem?

program to solve travelling salesman problem

All press is good press — until that press goes too well. Although the Netherlands’ beautiful, canal-filled city of Amsterdam garners about $91.5 billion a year through tourism, the city and its residents feel more overwhelmed than grateful. In 2018, a whopping 18 million people visited Amsterdam, and experts estimate that number will climb to 42 million visitors by 2030. Longtime resident Ellen van Loon told CNN , “We [the Dutch] don’t want to turn into a Venice.”

Italy’s similarly canaled destination attracts 28 million visitors annually — while 2,000 residents abandon the city each year due to those same tourists. Of course, Amsterdam and Venice aren’t the only cities that have become synonymous with overtourism. In fact, hotspots all over the world, from beaches in Thailand to ancient sites in Peru, have simply attracted too many curious tourists. This phenomenon, known as overtourism, has led to environmental and ecological damage as well as a great deal of strain for locals who must navigate living amongst tourists and their economic impact.

Of course, the COVID-19 pandemic has stymied travel, shutting down airports, cities, borders and entire nations. According to the U.S. Travel Association , travel spending declined by an unheard of 42% in 2020; international and business travel suffered the most, with spending falling 76% and 70%, respectively. So, after a year of virtually no tourism, how are these (normally too heavily traveled) places, and the people that call them home, faring?

How Overtourism Impacts Some of the World’s Most Beautiful Destinations

Be it an ancient site, a crowded city or a place of natural splendor, popular destinations all feel the effects of overtourism differently. For example, Rapa Nui — often known to westerners as Easter Island — faces preservation issues, especially when it comes to the island’s famed moai sculptures. Meanwhile, the Galápagos Islands, the fragile and isolated ecosystem Charles Darwin popularized, has put a cap on how many visitors can travel to the archipelago each year. And in hotspot cities like Barcelona, Spain, locals are so furious with the unprecedented jump in tourists that they’ve coined a term to describe what overtourism is doing to the city: parquetematización — or the act of becoming a theme park.

program to solve travelling salesman problem

Some of the other most heavily impacted destinations include:

How Has a Year Without Tourists Impacted These Normally Heavily Trafficked Places?

Cruises were one of the first aspects of the travel industry to shut down in 2020. In fact, the Centers for Disease Control and Prevention (CDC) found that between February 3 and March 13 roughly 200 COVID-19 cases in the U.S. were linked to cruise ship passengers. Soon enough, halts on air travel and widespread lockdowns followed.

program to solve travelling salesman problem

In Venice, a city that’s usually visited by upwards of 32,000 cruise ship passengers a day, the pandemic has completely changed the day-to-day energy of life there. “Everyday life is a lot more pleasant without the congestion created by the crowds of tourists that came in large groups,” Venice resident Jane da Mosto told CNN Travel .

Of course, that calmer way of life comes at a cost financially. The reprieve from tourists has had that same dual impact the world over. Now, in light of the pandemic, only 75 people are allowed in Machu Picchu at a time, which translates to just under 700 visitors a day. That’s hundreds less than the norm — and, while it’s better for the ancient site, the financial impact will certainly be felt. While experts predict that the travel industry will bounce back, COVID-19 has definitely upset the industry’s stability — largely because the pandemic, and various countries’ reactions to it, are so unpredictable.

Still, some see the pandemic as a disruption to a vicious, seemingly unbreakable cycle. With overtourism, governments often make tradeoffs to keep the cash flowing in, only to scramble for solutions to restore environments and structures or appease upset locals. With this in mind, World Politics Review brings up an interesting question: “Should business-as-usual be salvaged at any cost, or is now the chance to create a smaller, slower and more sustainable model of global tourism?” While the COVID-19 pandemic may have only put a temporary pause on tourism, the pause itself could be a chance to recalibrate, to figure out a way to end overtourism once and for all.

MORE FROM ASK.COM

program to solve travelling salesman problem

Related Articles

Travelling Salesman Problem using Dynamic Programming

Travelling Salesman Problem (TSP):  

Given a set of cities and the distance between every pair of cities, the problem is to find the shortest possible route that visits every city exactly once and returns to the starting point. Note the difference between Hamiltonian Cycle and TSP. The Hamiltonian cycle problem is to find if there exists a tour that visits every city exactly once. Here we know that Hamiltonian Tour exists (because the graph is complete) and in fact, many such tours exist, the problem is to find a minimum weight Hamiltonian Cycle. 

For example, consider the graph shown in the figure on the right side. A TSP tour in the graph is 1-2-4-3-1. The cost of the tour is 10+25+30+15 which is 80. The problem is a famous NP-hard problem. There is no polynomial-time know solution for this problem. The following are different solutions for the traveling salesman problem. 

Naive Solution:  

1) Consider city 1 as the starting and ending point.

2) Generate all (n-1)! Permutations of cities. 

3) Calculate the cost of every permutation and keep track of the minimum cost permutation. 

4) Return the permutation with minimum cost. 

Time Complexity: Θ(n!) 

Dynamic Programming:  

Let the given set of vertices be {1, 2, 3, 4,….n}. Let us consider 1 as starting and ending point of output. For every other vertex I (other than 1), we find the minimum cost path with 1 as the starting point, I as the ending point, and all vertices appearing exactly once. Let the cost of this path cost (i), and the cost of the corresponding Cycle would cost (i) + dist(i, 1) where dist(i, 1) is the distance from I to 1. Finally, we return the minimum of all [cost(i) + dist(i, 1)] values. This looks simple so far. 

Now the question is how to get cost(i)? To calculate the cost(i) using Dynamic Programming, we need to have some recursive relation in terms of sub-problems. 

Let us define a term C(S, i) be the cost of the minimum cost path visiting each vertex in set S exactly once, starting at 1 and ending at i . We start with all subsets of size 2 and calculate C(S, i) for all subsets where S is the subset, then we calculate C(S, i) for all subsets S of size 3 and so on. Note that 1 must be present in every subset.

Below is the dynamic programming solution for the problem using top down recursive+memoized approach:-

For maintaining the subsets we can use the bitmasks to represent the remaining nodes in our subset. Since bits are faster to operate and there are only few nodes in graph, bitmasks is better to use.

For example: –  

10100 represents node 2 and node 4 are left in set to be processed

010010 represents node 1 and 4 are left in subset.

NOTE:- ignore the 0th bit since our graph is 1-based

Time Complexity : O(n 2 *2 n ) 

Auxiliary Space : O(n 2 ) , where n is number of Nodes/Cities here.

For a set of size n, we consider n-2 subsets each of size n-1 such that all subsets don’t have nth in them. Using the above recurrence relation, we can write a dynamic programming-based solution. There are at most O(n*2 n ) subproblems, and each one takes linear time to solve. The total running time is therefore O(n 2 *2 n ). The time complexity is much less than O(n!) but still exponential. The space required is also exponential. So this approach is also infeasible even for a slightly higher number of vertices. We will soon be discussing approximate algorithms for the traveling salesman problem.

Next Article: Traveling Salesman Problem | Set 2  

References:  

http://www.lsi.upc.edu/~mjserna/docencia/algofib/P07/dynprog.pdf  

http://www.cs.berkeley.edu/~vazirani/algorithms/chap6.pdf  

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above

Solve DSA problems on GfG Practice.

Please Login to comment...

Prepare for Microsoft & other Product Based Companies

In JAVA/C++ Language

Improve your Coding Skills with Practice

Start your coding journey now.

Guru99

Travelling Salesman Problem: Python, C++ Algorithm

What is the travelling salesman problem (tsp).

Travelling Salesman Problem (TSP) is a classic combinatorics problem of theoretical computer science. The problem asks to find the shortest path in a graph with the condition of visiting all the nodes only one time and returning to the origin city.

The problem statement gives a list of cities along with the distances between each city.

Objective: To start from the origin city, visit other cities only once, and return to the original city again. Our target is to find the shortest possible path to complete the round-trip route.

Example of TSP

Here a graph is given where 1, 2, 3, and 4 represent the cities, and the weight associated with every edge represents the distance between those cities.

Travelling Salesman Problem (TSP)

The goal is to find the shortest possible path for the tour that starts from the origin city, traverses the graph while only visiting the other cities or nodes once, and returns to the origin city.

For the above graph, the optimal route is to follow the minimum cost path: 1-2-4-3-1. And this shortest route would cost 10+25+30+15 =80

Different Solutions to Travelling Salesman Problem

Travelling Salesman Problem (TSP)

Travelling Salesman Problem (TSP) is classified as a NP-hard problem due to having no polynomial time algorithm. The complexity increases exponentially by increasing the number of cities.

There are multiple ways to solve the traveling salesman problem (tsp). Some popular solutions are:

The brute force approach is the naive method for solving traveling salesman problems. In this approach, we first calculate all possible paths and then compare them. The number of paths in a graph consisting of n cities is n! It is computationally very expensive to solve the traveling salesman problem in this brute force approach.

The branch-and-bound method: The problem is broken down into sub-problems in this approach. The solution of those individual sub-problems would provide an optimal solution.

This tutorial will demonstrate a dynamic programming approach, the recursive version of this branch-and-bound method, to solve the traveling salesman problem.

Dynamic programming is such a method for seeking optimal solutions by analyzing all possible routes. It is one of the exact solution methods that solve traveling salesman problems through relatively higher cost than the greedy methods that provide a near-optimal solution.

The computational complexity of this approach is O(N^2 * 2^N) which is discussed later in this article.

The nearest neighbor method is a heuristic-based greedy approach where we choose the nearest neighbor node. This approach is computationally less expensive than the dynamic approach. But it does not provide the guarantee of an optimal solution. This method is used for near-optimal solutions.

Algorithm for Traveling Salesman Problem

We will use the dynamic programming approach to solve the Travelling Salesman Problem (TSP).

Before starting the algorithm, let’s get acquainted with some terminologies:

Let’s assume S is the subset of cities and belongs to {1, 2, 3, …, n} where 1, 2, 3…n are the cities and i, j are two cities in that subset. Now cost(i, S, j) is defined in such a way as the length of the shortest path visiting node in S, which is exactly once having the starting and ending point as i and j respectively.

For example, cost (1, {2, 3, 4}, 1) denotes the length of the shortest path where:

The dynamic programming algorithm would be:

cost(i, S, j)=min cost (i, S−{i}, j)+dist(i,j) where i∈S and i≠j

For the given figure, the adjacency matrix would be the following:

Travelling Salesman Problem (TSP)

Let’s see how our algorithm works:

Step 1) We are considering our journey starting at city 1, visit other cities once and return to city 1.

Step 2) S is the subset of cities. According to our algorithm, for all |S| > 1, we will set the distance cost(i, S, 1) = ∝. Here cost(i, S, j) means we are starting at city i, visiting the cities of S once, and now we are at city j. We set this path cost as infinity because we do not know the distance yet. So the values will be the following:

Cost (2, {3, 4}, 1) = ∝ ; the notation denotes we are starting at city 2, going through cities 3, 4, and reaching 1. And the path cost is infinity. Similarly-

cost(3, {2, 4}, 1) = ∝

cost(4, {2, 3}, 1) = ∝

Step 3) Now, for all subsets of S, we need to find the following:

cost(i, S, j)=min cost (i, S−{i}, j)+dist(i,j), where j∈S and i≠j

That means the minimum cost path for starting at i, going through the subset of cities once, and returning to city j. Considering that the journey starts at city 1, the optimal path cost would be= cost(1, {other cities}, 1).

Let’s find out how we could achieve that:

Now S = {1, 2, 3, 4}. There are four elements. Hence the number of subsets will be 2^4 or 16. Those subsets are-

1) |S| = Null:

2) |S| = 1:

{{1}, {2}, {3}, {4}}

3) |S| = 2:

{{1, 2}, {1, 3}, {1, 4}, {2, 3}, {2, 4}, {3, 4}}

4) |S| = 3:

{{1, 2, 3}, {1, 2, 4}, {2, 3, 4}, {1, 3, 4}}

5) |S| = 4:

{{1, 2, 3, 4}}

As we are starting at 1, we could discard the subsets containing city 1.

The algorithm calculation:

1) |S| = Φ:

cost (2, Φ, 1) = dist(2, 1) = 10

cost (3, Φ, 1) = dist(3, 1) = 15

cost (4, Φ, 1) = dist(4, 1) = 20

cost (2, {3}, 1) = dist(2, 3) + cost (3, Φ, 1) = 35+15 = 50

cost (2, {4}, 1) = dist(2, 4) + cost (4, Φ, 1) = 25+20 = 45

cost (3, {2}, 1) = dist(3, 2) + cost (2, Φ, 1) = 35+10 = 45

cost (3, {4}, 1) = dist(3, 4) + cost (4, Φ, 1) = 30+20 = 50

cost (4, {2}, 1) = dist(4, 2) + cost (2, Φ, 1) = 25+10 = 35

cost (4, {3}, 1) = dist(4, 3) + cost (3, Φ, 1) = 30+15 = 45

cost (2, {3, 4}, 1) = min [ dist[2,3]+Cost(3,{4},1) = 35+50 = 85,

dist[2,4]+Cost(4,{3},1) = 25+45 = 70 ] = 70

cost (3, {2, 4}, 1) = min [ dist[3,2]+Cost(2,{4},1) = 35+45 = 80,

dist[3,4]+Cost(4,{2},1) = 30+35 = 65 ] = 65

cost (4, {2, 3}, 1) = min [ dist[4,2]+Cost(2,{3},1) = 25+50 = 75

dist[4,3]+Cost(3,{2},1) = 30+45 = 75 ] = 75

cost (1, {2, 3, 4}, 1) = min [ dist[1,2]+Cost(2,{3,4},1) = 10+70 = 80

dist[1,3]+Cost(3,{2,4},1) = 15+65 = 80

dist[1,4]+Cost(4,{2,3},1) = 20+75 = 95 ] = 80

So the optimal solution would be 1-2-4-3-1

Travelling Salesman Problem (TSP)

Pseudo-code

Implementation in c/c++.

Here’s the implementation in C++:

Implementation in Python:

Academic solutions to tsp.

Computer scientists have spent years searching for an improved polynomial time algorithm for the Travelling Salesman Problem. Until now, the problem is still NP-hard.

Though some of the following solutions were published in recent years that have reduced the complexity to a certain degree:

Application of Traveling Salesman Problem

Travelling Salesman Problem (TSP) is applied in the real world in both its purest and modified forms. Some of those are:

Complexity Analysis of TSP

So the total time complexity for an optimal solution would be the Number of nodes * Number of subproblems * time to solve each sub-problem. The time complexity can be defined as O(N 2 * 2^N).

You Might Like:

program to solve travelling salesman problem

Travelling Salesman Problem in C and C++

Here you will learn about Travelling Salesman Problem (TSP) with example and also get a program that implements Travelling Salesman Problem in C and C++.

Travelling Salesman Problem (TSP) Using Dynamic Programming

Example problem.

Above we can see a complete directed graph and cost matrix which includes distance between each village. We can observe that cost matrix is symmetric that means distance between village 2 to 3 is same as distance between village 3 to 2.

T ( 4, {2} ) =  (4,2) + T (2, {} )     1+0 = 1

T ( 2, {3} ) =  (2,3) + T (3, {} )     2+0 = 2

Minimum distance is 7 which includes path 1->3->2->4->1.

After solving example problem we can easily write recursive equation.

Please enable JavaScript

Recursive Equation

But it is not guarantee that every vertex is connected to other vertex then we take that cost as infinity. After that we are taking minimum among all so the path which is not connected get infinity in calculation and won’t be consider.

Time Complexity

Here after reaching i th node finding remaining minimum distance to that i th node is a sub-problem.

Program for Travelling Salesman Problem in C

Enter Elements of Row: 4 3 1 5 0 The cost list is: 0 4 1 3 4 0 2 1 1 2 0 5 3 1 5 0

Program for Travelling Salesman Problem in C++

You may also like:, 48 thoughts on “travelling salesman problem in c and c++”, leave a comment cancel reply.

InterviewBit

Travelling Salesman Problem (TSP)

Problem statement, simple approach, c++ implementation, java implementation, python implementation, travelling salesman problem using dynamic programming, c implementation of dp approach, c++ implementation of dp approach, python implementation of dp approach, java implementation of dp approach, greedy approach, c++ implementation of greedy approach, java implementation of greedy approach, python implementation of greedy approach, practice questions, frequently asked questions.

Given a set of cities and distance between every pair of cities as an adjacency matrix, the problem is to find the shortest possible route that visits every city exactly once and returns to the starting point.

Travelling Salesman Problem Example 1

Input –

Confused about your next job?

Output –

TSP Example 2 – Input –

Output – Minimum weight Hamiltonian Cycle : EACBDE= 32

Time complexity: O(N!), Where N is the number of cities. Space complexity: O(1).

In travelling salesman problem algorithm, we take a subset N of the required cities that need to be visited, the distance among the cities dist, and starting city s as inputs. Each city is identified by a unique city id which we say like 1,2,3,4,5………n

Here we use a dynamic approach to calculate the cost function Cost(). Using recursive calls, we calculate the cost function for each subset of the original problem.

To calculate the cost(i) using Dynamic Programming , we need to have some recursive relation in terms of sub-problems.

We start with all subsets of size 2 and calculate C(S, i) for all subsets where S is the subset, then we calculate C(S, i) for all subsets S of size 3 and so on.

There are at most O(n2^n) subproblems, and each one takes linear time to solve. The total running time is, therefore, O(n^22^n). The time complexity is much less than O(n!) but still exponential. The space required is also exponential.

Time Complexity: O(N^2*2^N).

Time complexity: O(N^2*logN), Where N is the number of cities. Space complexity: O(N).

Q: Which algorithm is used for the Travelling salesman problem? A: Travelling Salesman Problem uses Dynamic programming with masking algorithm.

Q: What is the complexity of the Travelling salesman problem? A: The complexity of TSP using Greedy will be O(N^2 LogN) and using DP will be O(N^2 2^N).

Q: How is this problem modeled as a graph problem?

A: The TSP can be modeled as a graph problem by considering a complete graph G = (V, E).A tour is then a circuit in G that meets every node. In this context, tours are sometimes called Hamiltonian circuits.

Q: What is the difficulty level of the Travelling salesman problem? A: It is an NP-hard problem.

Previous Post

Gcd of two numbers (c, python, java) with examples, ​​​​difference between c and java.

Google OR-Tools

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.

program to solve travelling salesman problem

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:

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:

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.

Complete programs

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.

Solution printer

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.

Main function

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.

program to solve travelling salesman problem

Towards Data Science

Pedram Ataee, PhD

Jun 14, 2020

Member-only

Notes From Industry

How to solve the traveling salesman problem — a comparative analysis, through 3 optimization methods: dynamic programming, simulated annealing, and 2-opt..

I am sure you already heard about the traveling salesman problem or TSP. There are many applications for this problem and also many solutions with different performances. Here, I want to share my recent experience to solve the traveling salesman problem, especially with the 2-opt method which is one of the easiest, yet most effective, methods to solve this problem.

If you just want to read about the 2-opt, you can jump directly to the end of this article. You can also use the Python package that I developed below to solve a TSP.

In optimization, 2-opt is a simple local search algorithm with a special swapping mechanism that suits well to solve the…

In this article, I want to share my experience in solving a TSP with 120 cities to visit. The problem had to be solved in less than 5 minutes to be used in practice. I aimed to solve this problem with the following methods:

First, let me explain TSP in brief.

Artificial Intelligence: Unorthodox Lessons: How to Gain Insight and Build Innovative Solutions

Amazon.com: artificial intelligence: unorthodox lessons: how to gain insight and build innovative solutions ebook ….

www.amazon.com

Traveling Salesman Problem

The traveling salesman problem is a classic problem in combinatorial optimization. This problem is to find the shortest path that a salesman should take to traverse through a list of cities and return to the origin city. The list of cities and the distance between each pair are provided.

TSP is useful in various applications in real life such as planning or logistics. For example, a concert tour manager who wants to schedule a series of performances for the band must determine the shortest path for the tour to ensure reducing traveling costs and not make the band unnecessarily exhausted.

This is an NP-hard problem. In simple words, it means you can not guarantee to find the shortest path within a reasonable time limit. This is not unique to TSP though. In real-world optimization problems, you frequently encounter problems for which you must find sub-optimal solutions instead of optimal ones.

I. Dynamic Programming

The dynamic programming or DP method guarantees finding the best answer to TSP. However, its time complexity would exponentially increase with the number of cities. The time complexity with the DP method asymptotically equals N² × 2^N where N is the number of cities.

To give you a hint of how this time complexity increases, let me share my experiments. TSP with 10 cities can be solved by a DP method in almost 0.2 seconds using intel core i7. This number increases to almost 13 seconds (~60 times greater) with 15 cities. That is, the time complexity significantly increases even with a small increment in the number of cities.

To optimize the DP method, I could have used the memoization technique. However, the memoization technique with a large number of cities needs a 2^N × 2^N matrix that can not be easily handled in memory.

Suggestion- If you want to solve traveling salesman problem with a large number of cities the dynamic programming method is not the best choice. The DP method can guarantee the global optimum but it just needs much time and computational power that we mostly can not afford in real-world problems.

II. Simulated Annealing

Simulated Annealing or SA is a heuristic search algorithm that is inspired by the annealing mechanism in the metallurgy industry. Annealing refers to a controlled cooling mechanism that leads to the desired state of the material. But, how does this map to an optimization problem?

The lesson that optimization experts learned from the annealing mechanism is to enforce more control over the search process contrary to the gradient descent algorithm with fixed rules. The SA method has two major rules explained below.

In the SA method, the search process must be continued until finding a good-enough solution or until reaching the stopping criteria. Plus, this method is sensitive to how its parameters including the search step and moving direction are formulated and tuned. SA method is a heuristic search algorithm and, therefore, it is sensitive to its initial point in the search space.

I implemented the SA method and tested it several times. In the end, I could not obtain a better result compared to the 2-opt method given the time constraints to execute. The 2-opt method was executed very fast.

Suggestion- The outcome of the simulated annealing method is sensitive to its parameters and its stopping criteria. A simulated annealing method is a powerful tool. But if you want to work with it, make sure you are aware of its flaws.

The 2-opt algorithm is a simple local search method with a special swapping mechanism that works as its heuristic. The main idea behind the 2-opt method is to remove path crossing in each neighborhood of cities. The 2-opt can be implemented easily and executed fast. For example, TSP with 120 cities can be solved in less than 5 seconds on the intel core i7 using this method. Here, “solved” means the algorithm converges to a good-enough solution that is a sub-optimal solution. The 2-opt method converges fast since it is deterministic in contrary to the SA method.

This method similar to other heuristic search algorithms does not guarantee to find the global optimum. The 2-opt method can be easily trapped in local optimums since it does not have a mechanism to jump out of them. Knowing all of these flaws, this method still works very well in TSP since its heuristic is very relevant, so effective, in this problem .

pdrm83/py2opt

The 2-opt method similar to other heuristic search algorithms is sensitive to its initial point in the search space. That means the final outcomes are changed by different initial points. I used a simple trick to work around this issue and to improve the results of the 2-opt method. I ran the method with different randomized initial points 10 times and selected the best result among them. By this approach, I reduced the sensitivity to the starting point to some extent.

Suggestion- The 2-opt method can be implemented easily and executed fast. Plus, it works much better than the expectation, especially when you decrease its sensitivity to the initial point in the search space. I highly suggest using this method to solve the TSP unless a good-enough result is not appropriate for you.

IV. Summary

The video below is a good summary of this article. You will enjoy watching it.

There are many methods to solve TSP. However, the above methods are the most common ones. I highly suggest the 2-opt method since it is implemented simply and executes fast. However, the simulated annealing method is very powerful if you can properly tune it and you do not have a time constraint to find the final result.

The last words- When you want to find a solution for any problem including TSP, always think about how a simple technique such as the 2-opt method can work well. Why? Because its heuristic is very well-suited to the problem.

Thanks for Reading!

If you like this post and want to support me…

Join Medium with my referral link — Pedram Ataee, PhD

As a medium member, a portion of your membership fee goes to writers you read, and you get full access to every story….

pedram-ataee.medium.com

More from Towards Data Science

Your home for data science. A Medium publication sharing concepts, ideas and codes.

About Help Terms Privacy

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store

Pedram Ataee, PhD

🤖 AI Architect 📚 Author of “Artificial Intelligence: Unorthodox Lessons” ❤️ Support my writings @ tinyurl.com/4cbeejnn

Text to speech

Data Structure

C++ Program to Solve Travelling Salesman Problem for Unweighted Graph

Travelling Salesman Problem use to calculate the shortest route to cover all the cities and return back to the origin city. This method is use to find the shortest path to cover all the nodes of a graph.

This is the program to find shortest route of a unweighted graph.

 Live Demo

Anvi Jain

0 Followers

Tutorials Point

IMAGES

  1. Can Optimized Routes Solve Travelling Salesman Problem?

    program to solve travelling salesman problem

  2. The Unsolved Travelling salesmen problem

    program to solve travelling salesman problem

  3. Video Lesson On Traveling Salesman Problem

    program to solve travelling salesman problem

  4. 😊 Travelling salesman problem 5 cities. The Traveling Salesman Problem. 2019-03-02

    program to solve travelling salesman problem

  5. R Code Traveling Salesman Problem

    program to solve travelling salesman problem

  6. Travelling Salesman Problem

    program to solve travelling salesman problem

VIDEO

  1. Traveling Salesman Problem

  2. Government Hires Them To Solve A Maths Problem That Can Destroy Society!

  3. Taif Ayad Khaleel Solve the travelling salesman problem with K Nearest Neighbor Algorithm

  4. IB MAI HL

  5. IB MAI HL

  6. Travelling Salesman Problem in graph theory & DAA

COMMENTS

  1. What Are the Six Steps of Problem Solving?

    The six steps of problem solving involve problem definition, problem analysis, developing possible solutions, selecting a solution, implementing the solution and evaluating the outcome. Problem solving models are used to address issues that...

  2. How Do You Solve a Problem When You Have Different Bases With the Same Exponents?

    When multiplying or dividing different bases with the same exponent, combine the bases, and keep the exponent the same. For example, X raised to the third power times Y raised to the third power becomes the product of X times Y raised to th...

  3. How Has a Year Without Tourists Impacted the Overtourism Problem?

    All press is good press — until that press goes too well. Although the Netherlands’ beautiful, canal-filled city of Amsterdam garners about $91.5 billion a year through tourism, the city and its residents feel more overwhelmed than grateful...

  4. Traveling Salesman Problem (TSP) Implementation

    Traveling Salesman Problem (TSP) Implementation · Consider city 1 as the starting and ending point. Since the route is cyclic, we can consider

  5. Travelling Salesman Problem using Dynamic Programming

    1) Consider city 1 as the starting and ending point. · 2) Generate all (n-1)! Permutations of cities. · 3) Calculate the cost of every permutation

  6. Travelling Salesman Problem: Python, C++ Algorithm

    Algorithm for Traveling Salesman Problem · Set cost(i, , i) = 0, which means we start and end at i, and the cost is 0. · When |S| > 1, we define

  7. Travelling Salesman Problem in C and C++

    Program for Travelling Salesman Problem in C ; #include<stdio.h> ; int ary[10][10],completed[10],n,cost=0; ; void takeInput(). { ; int i,j; ; printf("Enter the

  8. Travelling Salesman Problem (TSP)

    Simple Approach · Consider city 1 as the starting and ending point. · Now, we will generate all possible permutations of cities which are (n-1)!.

  9. Travelling Salesman Problem Solved Step by Step

    In this video, Kodeeswaran will help you solve the Traveling Salesman Problem step by step using Dynamic Programming.

  10. Traveling Salesperson Problem

    Traveling Salesperson Problem · Create the data · Create the routing model · Create the distance callback · Set the cost of travel · Set search

  11. Travelling salesman problem

    Travelling Salesman, by director Timothy Lanzone, is the story of four mathematicians hired by the U.S. government to solve the most elusive problem in computer

  12. How to Solve the Traveling Salesman Problem

    You can solve the traveling salesman problem or TSP with dynamic programming, simulated annealing, and 2-opt methods. My suggestion is the 2-opt method.

  13. Travelling Salesman Problem

    TSP is the travelling salesman problem consists of a salesperson and his travel to various cities. The salesperson must travel to each of the

  14. C++ Program to Solve Travelling Salesman Problem for Unweighted

    Begin Define a variable vr = 4 universally. Declare an integer function TSP to implement Travelling salesman Problem. Declare a graph grph[][]