# Travelling salesman problem using bfs

A traveler needs to visit all the cities from a list, where distances between all the cities are known and each city should be visited just once. What is the shortest possible route that he visits each city exactly once and returns to the origin city?

Travelling salesman problem is the most notorious computational problem. We can use brute-force approach to evaluate every possible tour and select the best one. For n number of vertices in a graph, there are n - 1! Instead of brute-force using dynamic programming approach, the solution can be obtained in lesser time, though there is no polynomial time algorithm. An edge e u, v represents that vertices u and v are connected. Distance between vertex u and v is d u, vwhich should be non-negative.

Suppose we have started at city 1 and after visiting some cities now we are in city j. Hence, this is a partial tour. We certainly need to know jsince this will determine which cities are most convenient to visit next. We also need to know all the cities visited so far, so that we don't repeat any of them.

Hence, this is an appropriate sub-problem. Now, let express C S, j in terms of smaller sub-problems. We need to start at 1 and end at j. We should select the next city in such a way that.

Select the path from 2 to 4 cost is 10 then go backwards. We get the minimum value for d [3, 1] cost is 6. Previous Page. Next Page.Travelling Salesman Problem TSP : Given a set of cities and distance between every pair of cities, the problem is to find the shortest possible route that visits every city exactly once and returns back to the starting point.

### Final Report

The Hamiltoninan cycle problem is to find if there exist 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 figure on right side. A TSP tour in the graph is The problem is a famous NP hard problem. There is no polynomial time know solution for this problem. Become industry ready at a student-friendly price. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

Writing code in comment? Please use ide. Python3 program to implement traveling salesman. This code is contributed by. Check out this Author's contributed articles.

Improved By : Blinkiisanjeev Load Comments. We use cookies to ensure you have the best browsing experience on our website. Python3 program to implement traveling salesman problem using naive approach.TSP is a famous math problem: Given a number of cities and the costs of traveling from any city to any other city, what is the cheapest round-trip route that visits each city exactly once and then returns to the starting city?

A genetic algorithm is a adaptive stochastic optimization algorithms involving search and optimization. The evolutionary algorithm applies the principles of evolution found in nature to the problem of finding an optimal solution to a Solver problem. The traveling salesman problem TSP is a problem in discrete or combinatorial optimisation. It is a prominent illustration of a class of problems in computational complexity theory which are hard to solve.

An equivalent formulation in terms of graph theory is: Given a complete weighted graph where the vertices would represent the cities, the edges would represent the roads, and the weights would be the cost or distance of that roadfind a Hamiltonian cycle with the least weight. It can be shown that the requirement of returning to the starting city does not change the computational complexity of the problem.

A related problem is the bottleneck traveling salesman problem: Find a Hamiltonian cycle in a weighted graph with the minimal length of the longest edge. CS Length. Length-crossoverPoint. Chromosome dummy. Abs cost-thisCost. ToString. PrintCity i, cities. Initialization.

7.3 Traveling Salesman Problem - Branch and Bound

TSPCompute. Below is the optimal solution for the GA algorithm. If you compile and run the program, the optimal solution will appear in the DOS window as follow. If we show the optimal solution in graph that is, we connect the cities in the orderthe graph will look like below:. View All. Yuan Wang Updated date Apr 13, Please feel free to re-use the source codes. CS using System; using System. Threading; using System.

Free trial. Try them free. Learn More. Next Recommended Article.Our implementation is aimed at dense complete weighted graphs and we achieved close to 2. Our initial project was to implement and compare performance of genetic algorithms using different programming models, however after discussion with a TA and half way into the design, turns out results depended more on the fine tuning of mutation constants rather than the parallelization hence we looked at other algorithms for TSP.

We did this because it would allow us to tackle challenges for dense graphs in particular, while studying performance in the context of a real-world application of the NP-hard TSP problem. The dataset is composed of random complete weighted graphs.

Each pair of edges in the complete graphs has to follow the triangle inequality property — in order to work on TSP as stretch goal afterwards. Triangle inequality : Let a, b and c be 3 nodes in the graph, and the function distance i,j that gives the distance edge weight between the nodes i and j. The triangle inequality is the following:. We also had already performed work on graphs using OpenMP assignment 3 and were interested to look further into this.

There were numerous challenges in implementing MST since we always hit the trade-off between memory and synchronization overhead, due to the dependencies between and within each iterations of the MST computation algorithm. In addition, complete graphs for the purpose of TSP are very dense, which intensifies this tradeoff. The section below explains the various design decisions we made along the process. We represented the graph as a matrix of labels, each label mapping to a corresponding edge start vertex, end vertex, weight, labeland a list of groups.

As part of iteratively optimizing the algorithm, we decided not to set up the matrix as a matrix of edge as each edge is a struct of 4 integers, whereas labels are simply an integer. Therefore, this way, we have a matrix 4 times smaller, which is going to be very important as a lot of computations are based on the matrix. We then just have to map labels to edges in a unique structure. As we contract vertices, their group changes to the head vertex.

Thus for each group, the min edge can be found in parallel using the matrix. Thus we can do parallel reads, and since the group of any vertex is changed only once, parallel writes to groups as well.

Note that the adding edge to the solution is wrapped in a critical section however. Note that when we contract some vertices, we now have multiple edges between two groups.

### How to use Genetic Algorithm for Traveling Salesman Problem

Note that 3 can be efficient initially, but once there are very few groups left it performs repeated work. In addition, the matrix model holds only one edge between any two groups. Given more time, we wanted to explore a hybrid approach that began with 3 and then switched to 2 inspired by the top-down and bottom-up mix in assignment 3. Then using this information and approach 2, we update the matrix if we find a smaller edge than the one currently between any two groups.

We made this sequential because this step has fairly high temporal locality since multiple edges between same groups are compared as they are contracted. Note that because of contraction we no longer do any work for some nodes and edges, hence we could possibly adopt a binary model. However based on our experimentation and results from a similar problem in BFS Assignment 3 ; since the number of edges and vertices are decreasing we chose the more efficient strategy of storing the valid group numbers and generating a new list of edges.

We believe this is a better trade-off from our experience with writing BFS. As a stretch goal, TSP has been implemented at the end of the project. The most complex part of it is the computation of the Eulerian circuit: we decided to implement it using a depth first algorithm. We were looking for speedup compared to the sequential version we initially implemented.

To do so, we tried with different number of nodes citiesand different number of threads.Travelling Salesman Problem TSP : Given a set of cities and distance between every pair of cities, the problem is to find the shortest possible route that visits every city exactly once and returns back to the starting point. The Hamiltoninan cycle problem is to find if there exist 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. The problem is a famous NP hard problem. There is no polynomial time know solution for this problem. Become industry ready at a student-friendly price. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

Writing code in comment? Please use ide. Python3 implementation of the approach. Function to find the minimum weight. If last node is reached and it has. Finally return to check for. Loop to traverse the adjacency list. Mark as visited. Mark ith node as unvisited. Boolean array to check if a node. Mark 0th node as visited. Find the minimum weight Hamiltonian Cycle. This code is contributed by mohit kumar. Write ans. Check out this Author's contributed articles. Load Comments. We use cookies to ensure you have the best browsing experience on our website.The travelling salesman problem also called the travelling salesperson problem  or TSP asks the following 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 travelling purchaser problem and the vehicle routing problem are both generalizations of TSP. In the theory of computational complexitythe decision version of the TSP where given a length Lthe task is to decide whether the graph has a tour of at most L belongs to the class of NP-complete problems. Thus, it is possible that the worst-case running time for any algorithm for the TSP increases superpolynomially but no more than exponentially with the number of cities.

The problem was first formulated in and is one of the most intensively studied problems in optimization. It is used as a benchmark for many optimization methods. The TSP has several applications even in its purest formulation, such as planninglogisticsand the manufacture of microchips. Slightly modified, it appears as a sub-problem in many areas, such as DNA sequencing. In these applications, the concept city represents, for example, customers, soldering points, or DNA fragments, and the concept distance represents travelling times or cost, or a similarity measure between DNA fragments. The TSP also appears in astronomy, as astronomers observing many sources will want to minimize the time spent moving the telescope between the sources.

In many applications, additional constraints such as limited resources or time windows may be imposed. The origins of the travelling salesman problem are unclear. A handbook for travelling salesmen from mentions the problem and includes example tours through Germany and Switzerlandbut contains no mathematical treatment.

The travelling salesman problem was mathematically formulated in the s by the Irish mathematician W. Hamilton and by the British mathematician Thomas Kirkman. We denote by messenger problem since in practice this question should be solved by each postman, anyway also by many travelers the task to find, for finitely many points whose pairwise distances are known, the shortest route connecting the points. Of course, this problem is solvable by finitely many trials.

Rules which would push the number of trials below the number of permutations of the given points, are not known. The rule that one first should go from the starting point to the closest point, then to the point closest to this, etc. It was first considered mathematically in the s by Merrill M. Flood who was looking to solve a school bus routing problem.

## Travelling salesman problem

The earliest publication using the phrase "traveling salesman problem" was the RAND Corporation report by Julia Robinson"On the Hamiltonian game a traveling salesman problem. Johnson from the RAND Corporation, who expressed the problem as an integer linear program and developed the cutting plane method for its solution.Travelling salesman problem is a problem of combinatorial optimization.

The goal of the travelling salesman is to find a cycle in a complete weighted graph, which goes through all its vertices and its cost is minimal. More formally: to find a minimal Hamiltonian circuit in a complete weighted graph. There are many cities in the given country and the travelling salesman has to visit all of them and return to his family in the original city.

There are roads built among all the cities on the map and the salesman wants to choose such a path that will be cheapest for him. The problem is NP-complete and strongly NP-hardwhich means that if holds, than for the travelling salesman problem does not exist any k -approximation algorithm — there is no algorithm, which is polynomial and always return a solution, which is in the worst case k times suboptimal.

The asymmetric travelling salesman problem can be formulated using integer linear programming. Asymmetric means that the weight of path from may be different than. The first two conditions guarantee that each node will be visited exactly once. The third one non-divisibility of the resulting Hamiltonian path the path can not form more than one cycle. Metric travelling salesman is a modification of the original problem, in which the distances within the graph respect the triangle inequality.

This simplification, which resembles many real problems distances on a map also respect the triangle inequalitymakes it possible to construct k -approximation algorithms. Problem of the metric travelling salesman problem can be easily solved 2-approximated in a polynomial time. At first the algorithm constructs a minimum spanning tree of the graph.

From the definition of a minimal spanning tree it arises thatbecause the spanning tree contains edges, while the cycle. Then the algorithm traverses the spanning tree from arbitrary node using depth first search and memorizes all traverses through individual nodes — from the nature of depth first search it comes that some nodes will be processed more than once.

In the last step — compression of paths — the algorithm walks through the list of nodes created in the previous step and removes duplicities keeps in the list only first occurrences of each node. This way a cycle is created. Because the graph respects triangle inequality, the weight of the path is no more than twice as long as the original spanning tree.

The left part of the illustration shows a graph and its minimum spanning tree, which can be constructed using Kruskal's algorithm. Then the spanning tree was traversed using depth first search from node.

The algorithm returned the following sequence of nodes:. In the last step the paths were contracted in order to create a cycle. Christofides algorithm solves the problem of metric travelling salesman in such a way that the resulting cycle is at most times longer than the optimal one. This improvement is paid back by substantially more difficult implementation in comparison to the 2-approximation algorithm. Also experiments using real data show that these two algorithms produce in average comparable solutions.

Similarly to the 2-approximation algorithm the Christofides procedure at first constructs a minimal spanning tree of the graph. Than it traverses from the arbitrary node using depth first search and constructs a new complete graph from nodes with odd degree. Then the procedure finds minimum perfect matching of graph and adds edges from into the spanning tree.

The graph is now Eulerian there exists a trail which goes through all nodes of this graph. Finally the procedure finds Eulerian trail — the resulting path corresponds with the order of first visits of each node.

Motivation There are many cities in the given country and the travelling salesman has to visit all of them and return to his family in the original city.

Complexity The problem is NP-complete and strongly NP-hardwhich means that if holds, than for the travelling salesman problem does not exist any k -approximation algorithm — there is no algorithm, which is polynomial and always return a solution, which is in the worst case k times suboptimal. ILP formulation The asymmetric travelling salesman problem can be formulated using integer linear programming.

Subject to:. Home Graph algorithms.