Travelling Sales Man Problem
Travelling Sales Man Problem
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.
Algorithm:
1. Consider city 1 as the starting and ending point. Since the route is cyclic, we can
consider any point as a starting point.
2. Generate all (n-1)! permutations of cities.
3. Calculate the cost of every permutation and keep track of minimum cost permutation.
4. Return the permutation with minimum cost.
Java Implementation:
class GFG
{
// BACKTRACKING STEP
// Loop to traverse the adjacency list
// of currPos node and increasing the count
// by 1 and cost by graph[currPos,i] value
for (int i = 0; i < n; i++)
{
if (v[i] == false && graph[currPos][i] > 0)
{
// Mark as visited
v[i] = true;
ans = tsp(graph, v, i, n, count + 1,
cost + graph[currPos][i], ans);
// Driver code
public static void main(String[] args)
{