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 Hamiltonian 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:Â
Â
C++
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std;#define V 4Â
// Function to find the minimum weight Hamiltonian Cyclevoid tsp(int graph[][V], vector<bool>& v, int currPos,         int n, int count, int cost, int& ans){Â
    // If last node is reached and it has a link    // to the starting node i.e the source then    // keep the minimum value out of the total cost    // of traversal and "ans"    // Finally return to check for more possible values    if (count == n && graph[currPos][0]) {        ans = min(ans, cost + graph[currPos][0]);        return;    }Â
    // 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] && graph[currPos][i]) {Â
            // Mark as visited            v[i] = true;            tsp(graph, v, i, n, count + 1,                cost + graph[currPos][i], ans);Â
            // Mark ith node as unvisited            v[i] = false;        }    }};Â
// Driver codeint main(){Â Â Â Â // n is the number of nodes i.e. VÂ Â Â Â int n = 4;Â
    int graph[][V] = {        { 0, 10, 15, 20 },        { 10, 0, 35, 25 },        { 15, 35, 0, 30 },        { 20, 25, 30, 0 }    };Â
    // Boolean array to check if a node    // has been visited or not    vector<bool> v(n);    for (int i = 0; i < n; i++)        v[i] = false;Â
    // Mark 0th node as visited    v[0] = true;    int ans = INT_MAX;Â
    // Find the minimum weight Hamiltonian Cycle    tsp(graph, v, 0, n, 1, 0, ans);Â
    // ans is the minimum weight Hamiltonian Cycle    cout << ans;Â
    return 0;} |
Java
// Java implementation of the approachclass GFG {Â
    // Function to find the minimum weight     // Hamiltonian Cycle    static int tsp(int[][] graph, boolean[] v,                    int currPos, int n,                    int count, int cost, int ans)     {Â
        // If last node is reached and it has a link        // to the starting node i.e the source then        // keep the minimum value out of the total cost        // of traversal and "ans"        // Finally return to check for more possible values        if (count == n && graph[currPos][0] > 0)         {            ans = Math.min(ans, cost + graph[currPos][0]);            return ans;        }Â
        // 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);Â
                // Mark ith node as unvisited                v[i] = false;            }        }        return ans;    }Â
    // Driver code    public static void main(String[] args)    {Â
        // n is the number of nodes i.e. V        int n = 4;Â
        int[][] graph = {{0, 10, 15, 20},                         {10, 0, 35, 25},                         {15, 35, 0, 30},                         {20, 25, 30, 0}};Â
        // Boolean array to check if a node        // has been visited or not        boolean[] v = new boolean[n];Â
        // Mark 0th node as visited        v[0] = true;        int ans = Integer.MAX_VALUE;Â
        // Find the minimum weight Hamiltonian Cycle        ans = tsp(graph, v, 0, n, 1, 0, ans);Â
        // ans is the minimum weight Hamiltonian Cycle        System.out.println(ans);    }}Â
// This code is contributed by Rajput-Ji |
Python3
# Python3 implementation of the approachV = 4answer = []Â
# Function to find the minimum weight # Hamiltonian Cycledef tsp(graph, v, currPos, n, count, cost):Â
    # If last node is reached and it has     # a link to the starting node i.e     # the source then keep the minimum     # value out of the total cost of     # traversal and "ans"    # Finally return to check for     # more possible values    if (count == n and graph[currPos][0]):        answer.append(cost + graph[currPos][0])        returnÂ
    # 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 i in range(n):        if (v[i] == False and graph[currPos][i]):                         # Mark as visited            v[i] = True            tsp(graph, v, i, n, count + 1,                 cost + graph[currPos][i])                         # Mark ith node as unvisited            v[i] = FalseÂ
# Driver codeÂ
# n is the number of nodes i.e. Vif __name__ == '__main__':    n = 4    graph= [[ 0, 10, 15, 20 ],            [ 10, 0, 35, 25 ],            [ 15, 35, 0, 30 ],            [ 20, 25, 30, 0 ]]Â
    # Boolean array to check if a node    # has been visited or not    v = [False for i in range(n)]         # Mark 0th node as visited    v[0] = TrueÂ
    # Find the minimum weight Hamiltonian Cycle    tsp(graph, v, 0, n, 1, 0)Â
    # ans is the minimum weight Hamiltonian Cycle    print(min(answer))Â
# This code is contributed by mohit kumar |
C#
// C# implementation of the approachusing System;Â
class GFG{Â
// Function to find the minimum weight Hamiltonian Cyclestatic int tsp(int [,]graph, bool []v, int currPos,        int n, int count, int cost, int ans){Â
    // If last node is reached and it has a link    // to the starting node i.e the source then    // keep the minimum value out of the total cost    // of traversal and "ans"    // Finally return to check for more possible values    if (count == n && graph[currPos,0] > 0)     {        ans = Math.Min(ans, cost + graph[currPos,0]);        return ans;    }Â
    // 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);Â
            // Mark ith node as unvisited            v[i] = false;        }    }    return ans;}Â
// Driver codestatic void Main(){Â Â Â Â // n is the number of nodes i.e. VÂ Â Â Â int n = 4;Â
    int [,]graph = {        { 0, 10, 15, 20 },        { 10, 0, 35, 25 },        { 15, 35, 0, 30 },        { 20, 25, 30, 0 }    };Â
    // Boolean array to check if a node    // has been visited or not    bool[] v = new bool[n];Â
    // Mark 0th node as visited    v[0] = true;    int ans = int.MaxValue;Â
    // Find the minimum weight Hamiltonian Cycle    ans = tsp(graph, v, 0, n, 1, 0, ans);Â
    // ans is the minimum weight Hamiltonian Cycle    Console.Write(ans);Â
}}Â
// This code is contributed by mits |
Javascript
<script>Â
// Javascript implementation of the approachvar V = 4;var ans = 1000000000;// Boolean array to check if a node// has been visited or notvar v = Array(n).fill(false);// Mark 0th node as visitedv[0] = true;Â
// Function to find the minimum weight Hamiltonian Cyclefunction tsp(graph, currPos, n, count, cost){Â
    // If last node is reached and it has a link    // to the starting node i.e the source then    // keep the minimum value out of the total cost    // of traversal and "ans"    // Finally return to check for more possible values    if (count == n && graph[currPos][0]) {        ans = Math.min(ans, cost + graph[currPos][0]);        return;    }Â
    // 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 (var i = 0; i < n; i++) {        if (!v[i] && graph[currPos][i]) {Â
            // Mark as visited            v[i] = true;            tsp(graph, i, n, count + 1,                cost + graph[currPos][i]);Â
            // Mark ith node as unvisited            v[i] = false;        }    }};Â
// Driver code// n is the number of nodes i.e. Vvar n = 4;var graph = [    [ 0, 10, 15, 20 ],    [ 10, 0, 35, 25 ],    [ 15, 35, 0, 30 ],    [ 20, 25, 30, 0 ]];Â
// Find the minimum weight Hamiltonian Cycletsp(graph, 0, n, 1, 0);// ans is the minimum weight Hamiltonian Cycledocument.write( ans);Â
</script> |
80
Â
Time Complexity: O(N!), As for the first node there are N possibilities and for the second node there are n – 1 possibilities.
For N nodes time complexity = N * (N – 1) * . . . 1 = O(N!)
Auxiliary Space: O(N)
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!


… [Trackback]
[…] Read More here on that Topic: geeksforgeeks.org/travelling-salesman-problem-implementation-using-backtracking/ […]
… [Trackback]
[…] Read More on that Topic: geeksforgeeks.org/travelling-salesman-problem-implementation-using-backtracking/ […]
… [Trackback]
[…] Find More Information here to that Topic: geeksforgeeks.org/travelling-salesman-problem-implementation-using-backtracking/ […]