# Traveling Salesman Problem (TSP) Implementation

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 figure on 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.

Examples:

Output of Given Graph: minimum weight Hamiltonian Cycle : 10 + 25 + 30 + 15 := 80

In this post, implementation of simple solution is discussed.

- Consider city 1 as the starting and ending point. Since route is cyclic, we can consider any point as starting point.
- Generate all (n-1)! permutations of cities.
- Calculate cost of every permutation and keep track of minimum cost permutation.
- Return the permutation with minimum cost.

Below is the implementation of above idea

## C++

`// CPP program to implement traveling salesman ` `// problem using naive approach. ` `#include <bits/stdc++.h> ` `using` `namespace` `std; ` `#define V 4 ` ` ` `// implementation of traveling Salesman Problem ` `int` `travllingSalesmanProblem(` `int` `graph[][V], ` `int` `s) ` `{ ` ` ` `// store all vertex apart from source vertex ` ` ` `vector<` `int` `> vertex; ` ` ` `for` `(` `int` `i = 0; i < V; i++) ` ` ` `if` `(i != s) ` ` ` `vertex.push_back(i); ` ` ` ` ` `// store minimum weight Hamiltonian Cycle. ` ` ` `int` `min_path = INT_MAX; ` ` ` `do` `{ ` ` ` ` ` `// store current Path weight(cost) ` ` ` `int` `current_pathweight = 0; ` ` ` ` ` `// compute current path weight ` ` ` `int` `k = s; ` ` ` `for` `(` `int` `i = 0; i < vertex.size(); i++) { ` ` ` `current_pathweight += graph[k][vertex[i]]; ` ` ` `k = vertex[i]; ` ` ` `} ` ` ` `current_pathweight += graph[k][s]; ` ` ` ` ` `// update minimum ` ` ` `min_path = min(min_path, current_pathweight); ` ` ` ` ` `} ` `while` `(next_permutation(vertex.begin(), vertex.end())); ` ` ` ` ` `return` `min_path; ` `} ` ` ` `// driver program to test above function ` `int` `main() ` `{ ` ` ` `// matrix representation of graph ` ` ` `int` `graph[][V] = { { 0, 10, 15, 20 }, ` ` ` `{ 10, 0, 35, 25 }, ` ` ` `{ 15, 35, 0, 30 }, ` ` ` `{ 20, 25, 30, 0 } }; ` ` ` `int` `s = 0; ` ` ` `cout << travllingSalesmanProblem(graph, s) << endl; ` ` ` `return` `0; ` `} ` |

*chevron_right*

*filter_none*

## Python3

`# Python3 program to implement traveling salesman ` `# problem using naive approach. ` `from` `sys ` `import` `maxsize ` `V ` `=` `4` ` ` `# implementation of traveling Salesman Problem ` `def` `travellingSalesmanProblem(graph, s): ` ` ` ` ` `# store all vertex apart from source vertex ` ` ` `vertex ` `=` `[] ` ` ` `for` `i ` `in` `range` `(V): ` ` ` `if` `i !` `=` `s: ` ` ` `vertex.append(i) ` ` ` ` ` `# store minimum weight Hamiltonian Cycle ` ` ` `min_path ` `=` `maxsize ` ` ` ` ` `while` `True` `: ` ` ` ` ` `# store current Path weight(cost) ` ` ` `current_pathweight ` `=` `0` ` ` ` ` `# compute current path weight ` ` ` `k ` `=` `s ` ` ` `for` `i ` `in` `range` `(` `len` `(vertex)): ` ` ` `current_pathweight ` `+` `=` `graph[k][vertex[i]] ` ` ` `k ` `=` `vertex[i] ` ` ` `current_pathweight ` `+` `=` `graph[k][s] ` ` ` ` ` `# update minimum ` ` ` `min_path ` `=` `min` `(min_path, current_pathweight) ` ` ` ` ` `if` `not` `next_permutation(vertex): ` ` ` `break` ` ` ` ` `return` `min_path ` ` ` `# next_permutation implementation ` `def` `next_permutation(L): ` ` ` ` ` `n ` `=` `len` `(L) ` ` ` ` ` `i ` `=` `n ` `-` `2` ` ` `while` `i >` `=` `0` `and` `L[i] >` `=` `L[i ` `+` `1` `]: ` ` ` `i ` `-` `=` `1` ` ` ` ` `if` `i ` `=` `=` `-` `1` `: ` ` ` `return` `False` ` ` ` ` `j ` `=` `i ` `+` `1` ` ` `while` `j < n ` `and` `L[j] > L[i]: ` ` ` `j ` `+` `=` `1` ` ` `j ` `-` `=` `1` ` ` ` ` `L[i], L[j] ` `=` `L[j], L[i] ` ` ` ` ` `left ` `=` `i ` `+` `1` ` ` `right ` `=` `n ` `-` `1` ` ` ` ` `while` `left < right: ` ` ` `L[left], L[right] ` `=` `L[right], L[left] ` ` ` `left ` `+` `=` `1` ` ` `right ` `-` `=` `1` ` ` ` ` `return` `True` ` ` `# Driver Code ` `if` `__name__ ` `=` `=` `"__main__"` `: ` ` ` ` ` `# matrix representation of graph ` ` ` `graph ` `=` `[[` `0` `, ` `10` `, ` `15` `, ` `20` `], [` `10` `, ` `0` `, ` `35` `, ` `25` `], ` ` ` `[` `15` `, ` `35` `, ` `0` `, ` `30` `], [` `20` `, ` `25` `, ` `30` `, ` `0` `]] ` ` ` `s ` `=` `0` ` ` `print` `(travellingSalesmanProblem(graph, s)) ` ` ` `# This code is contributed by ` `# sanjeev2552 ` |

*chevron_right*

*filter_none*

**Output:**

80

GeeksforGeeks has prepared a complete interview preparation course with premium videos, theory, practice problems, TA support and many more features. Please refer Placement 100 for details

## Recommended Posts:

- Traveling Salesman Problem using Genetic Algorithm
- Travelling Salesman Problem implementation using BackTracking
- Travelling Salesman Problem | Set 2 (Approximate using MST)
- Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)
- Exact Cover Problem and Algorithm X | Set 2 (Implementation with DLX)
- Implementation of BFS using adjacency matrix
- Implementation of Graph in JavaScript
- Push Relabel Algorithm | Set 2 (Implementation)
- Karger's algorithm for Minimum Cut | Set 1 (Introduction and Implementation)
- Bellman Ford Algorithm (Simple Implementation)
- Graph implementation using STL for competitive programming | Set 1 (DFS of Unweighted and Undirected)
- Kruskal's Algorithm (Simple Implementation for Adjacency Matrix)
- Johnson’s algorithm for All-pairs shortest paths | Implementation
- Hopcroft–Karp Algorithm for Maximum Matching | Set 2 (Implementation)
- Prim's Algorithm (Simple Implementation for Adjacency Matrix Representation)

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. 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.