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.
Note the difference between Hamiltonian Cycle and TSP. 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. 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.
Output of Given Graph:
Minimum weight Hamiltonian Cycle : 10 + 25 + 30 + 15 = 80
Approach: In this post, implementation of simple solution is discussed.
- Consider city 1 (let say 0th node) as the starting and ending point. Since route is cyclic, we can consider any point as starting point.
- Start traversing from the source to its adjacent nodes in dfs manner.
- Calculate cost of every traversal and keep track of minimum cost and keep on updating the value of minimum cost stored value.
- Return the permutation with minimum cost.
Below is the implementation of the above approach:
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Travelling Salesman Problem | Set 2 (Approximate using MST)
- Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)
- Travelling Salesman Problem | Greedy Approach
- Traveling Salesman Problem (TSP) Implementation
- Traveling Salesman Problem using Genetic Algorithm
- Proof that traveling salesman problem is NP Hard
- Word Break Problem using Backtracking
- The Knight's tour problem | Backtracking-1
- N Queen Problem | Backtracking-3
- m Coloring Problem | Backtracking-5
- Rat in a Maze | Backtracking using Stack
- Maximal independent set from a given Graph using Backtracking
- Maximum size subset with given sum using Backtracking
- Generate all distinct subsequences of array using backtracking
- Exact Cover Problem and Algorithm X | Set 2 (Implementation with DLX)
- Rat in a Maze | Backtracking-2
- Sudoku | Backtracking-7
- Subset Sum | Backtracking-4
- Hamiltonian Cycle | Backtracking-6
- Solving Cryptarithmetic Puzzles | Backtracking-8
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. 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.