Travelling Salesman Problem | Practice | GeeksforGeeks

Given a matrix cost of size n where cost[i][j] denotes the cost of moving from city i to city j. Your task is to complete a tour from the city 0 (0 based index) to all other cities such that you visit each city atmost once and then at the end come back to city 0 in min cost.
 
Example 1:
Input: cost = {{0,111},{112,0}}
Output: 223
Explanation: We can visit 0->1->0 and 
cost = 111 + 112.

Example 2:
Input: cost = {{0,1000,5000},{5000,0,1000},
{1000,5000,0}}
Output: 3000
Explanation: We can visit 0->1->2->0 and cost 
= 1000+1000+1000 = 3000

 
Your Task:
You don't need to read or print anyhting. Your task is to complete the function total_cost() which takes cost as input parameter and returns the total cost to visit each city exactly once starting from city 0 and again comback to city 0.
 
Expected Time Complexity: O(2n * n2)
Expected Space Compelxity: O(2n * n)
 
Constraints:
1 <= n <= 10
1 <= cost[i][j] <= 103
0
dattatraygujar772 weeks ago
public int min=Integer.MAX_VALUE;
    public void solve(int cost[][], HashSet<Integer> set,int ans,int i)
    {
         if(ans>min) return ;
           if(set.size()==cost.length)
           {
               min=Math.min(min,ans+cost[i][0]);
               return;
           }
        for(int j=1;j<cost.length;j++)
        {
           if(!set.contains(j))
           {
             set.add(j);
             ans+=cost[i][j];
             solve(cost,set,ans,j);
             set.remove(j);
             ans=ans-cost[i][j];
           }
        }
       
    }
    public int total_cost(int[][] cost)
    {
        HashSet<Integer> set=new HashSet<>();
        set.add(0);
        int ans=0;
     solve(cost,set,ans,0);
     return min;
    }
 
+1
avinashdhn19042 weeks ago
// solution using dp with bitmasking


int dp[1<<11][11];
class Solution {
public:
int tsp(int mask,int pos,vector<vector<int>>cost,int n){
    if(mask==((1<<n)-1))return cost[pos][0];
    if(dp[mask][pos]!=-1)return dp[mask][pos];
    int ans=INT_MAX;
    for(int city=0;city<n;city++){
        if(!(mask&(1<<city))){
            int tmp=cost[pos][city]+tsp((mask|(1<<city)),city,cost,n);
            ans=min(ans,tmp);
        }
    }
    return dp[mask][pos]=ans;
}
int total_cost(vector<vector<int>>cost){
    memset(dp,-1,sizeof(dp));
    int n=cost.size();
    return tsp(1,0,cost,n);
}
};
 
+1
rohitshinde1803011 month ago
class Solution {public:int solve(vector<vector<int>>&cost, int i, int no_of_cities, vector<bool>& visited){   const int n = cost.size();   //when we reach all cities, then its time to return to the city from where we started   if(no_of_cities==n)        return cost[i][0];
   int ans=INT_MAX;   visited[i] = true;   for(int j=0;j<n;j++){       if(!visited[j]){           visited[j] = true;           ans = min(ans, cost[i][j] + solve(cost, j, no_of_cities+1, visited));           visited[j] = false;       }   }   visited[i] = false;   return ans;}int total_cost(vector<vector<int>>cost){   // Code here   vector<bool> visited(cost.size(), false);   //we are starting from city 0   //"i" represent current city in above solve() function   return solve(cost, 0, 1, visited);}};
0
anshul gupta 61 month ago
 public int solve(int[][] cost, int sum, List<Integer> list, int index) {
        if (list.size() == cost.length - 1)
            return sum + cost[list.get(list.size() - 1)][0];
        int min = Integer.MAX_VALUE;
        for (int i = 1; i < cost.length; i++) {
            if (i != index && !list.contains(i)) {
                list.add(i);
                min = Math.min(min, solve(cost, sum + cost[index][i], list, i));
                list.remove(list.size() - 1);
            }
        }
        return min;
    }
    public int total_cost(int[][] cost)
    {
        if(cost.length==1)
            return 0;
        return solve(cost, 0, new ArrayList<>(), 0);
    }
+1
aloksinghbais022 months ago
C++ solution using Hamiltonian Cycle using bit masking, backtracking is as follows :- 
 
Execution Time :- 0.2 / 3.4 sec
 
int minCost;   int vis;      void dfs(int node,int cost,int val,vector<pair<int,int>> adj[],vector<vector<int>> &ct){       vis = vis | (1 << (node));              for(auto choice: adj[node]){           int n = choice.first;           int c = choice.second;           if((vis & (1<<n)) == 0){               dfs(n,cost+c,val,adj,ct);               vis = vis ^ (1<<n);           }           else{              if(vis == val && n == 0){                   minCost = min(minCost,cost + ct[node][n]);               }           }       }   }      int total_cost(vector<vector<int>>cost){       int n = cost.size();       if(n == 1) return (0);       vector<pair<int,int>> adj[n];       for(int i = 0; i < n; i++){           for(int j = 0; j < n; j++){               if(cost[i][j] != 0){                   adj[i].push_back({j,cost[i][j]});               }           }       }              vis = 0;       minCost = INT_MAX;       dfs(0,0,(1<<n)-1,adj,cost);              return (minCost);   }
0
guptaravi32173 months ago
     // JAVA Solution 
    // HashSet , backtracking Solution
     int min = Integer.MAX_VALUE;   public  int total_cost(int[][] cost) {       HashSet<Integer> set = new HashSet<>();       int n = cost.length - 1;       for (int i = 1; i <= n; i++) {           set.add(i);       }       for (int i = 1; i <= n; i++) {           findMinimumCost(i, cost, cost[0][i], set);       }       return min == Integer.MAX_VALUE? 0 : min;   }
   public  void findMinimumCost(int i, int[][] matrix, int cost, HashSet<Integer> set) {//        System.out.println(i + "   " + set + "  " + cost);       if (set.size() == 1) {           for (int val : set) {               min = Math.min(min, matrix[i][0] + cost);           }//            System.out.println(min);           return;       }       set.remove(i);       HashSet<Integer> cloned_set = new HashSet<>();       cloned_set = (HashSet) set.clone();       for (int key : cloned_set) {           findMinimumCost(key, matrix, cost + matrix[i][key], set);       }       set.add(i);   }
0
utkarshrdce3 months ago
DP with bitmask
 
class Solution {
public:
int dp[11][1<<11];

int f(int i, int mask, vector<vector<int>> &cost) {
    if(mask  == 0) return cost[i][0];
    if(dp[i][mask] != -1) return dp[i][mask];
    
    int curAns = INT_MAX;
    for(int j = 31; j >= 0; j--) {
        if((mask & (1 << j))) {
            curAns = min(curAns, cost[i][j] + f(j, mask ^ (1 << j), cost));
        }
    }
    return dp[i][mask] = curAns;
    
}
int total_cost(vector<vector<int>>cost){
    // Code here
    memset(dp, -1, sizeof(dp));
    int n = cost.size();
    int current_mask = (1 << n) - 1;
    current_mask = current_mask ^ (1 << 0);
    return f(0, current_mask, cost);
    
    
}
};
-3
kunal04033 months ago
Any iterative dp+bitmask solution ?
+1
imansaboori5 months ago
class Solution {
public:
int solve(vector<vector<int>>&cost, int i, int depth, vector<bool>& visited)
{
    const int n = cost.size();
    if(depth==n)
        return cost[i][0];

    int ans=INT_MAX;
    visited[i] = true;
    for(int j=0;j<n;j++)
    {
        if(!visited[j])
        {
            visited[j] = true;
            ans = min(ans, cost[i][j] + solve(cost, j, depth+1, visited));
            visited[j] = false;
        }
    }
    visited[i] = false;
    return ans;
}
int total_cost(vector<vector<int>>cost){
    // Code here
    vector<bool> visited(cost.size(), false);
    return solve(cost, 0, 1, visited);
}
};
+2
amanshakya0076 months ago
Dynamic Programming , Graph and BackTracking 
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.