Travelling Salesman Problem implementation using BackTracking (original) (raw)
Last Updated : 11 Jul, 2025
Given a 2d matrix cost[][] of **size n where **cost[i][j] denotes the cost of moving from city i to city j. The task is to complete a tour from **city 0 (0-based index) to all other cities such that we visit each city exactly once and then at the end come back to city 0 at minimum cost.
Note the difference between Hamiltonian Cycle and **TSP. The **Hamiltonian cycle problem is to find if there **exists 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.
**Examples:
**Input: cost[][] = [[0, 111], [112, 0]]
**Output: 223
**Explanation: We can visit 0->1->0 and cost = 111 + 112 = 223.**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.
**Approach:
To solve the problem, we start by considering **city 1 ****(the 0th node)** as both the **starting and **ending point, given the **cyclic nature of the route, which makes any node a valid starting point. The solution involves a **Depth-First Search (DFS) approach, where we **recursively explore **all possible paths from the starting node to its **adjacent nodes. During each traversal, we calculate the **cumulative cost of visiting nodes and ensure that nodes are visited only once, except for returning to the **starting point to complete the cycle. If all nodes have been visited and there is a path back to the starting point, the total cost of that cycle is calculated. We keep track of the minimum cost among all valid cycles, updating it whenever **a smaller cost is found.
C++ `
// C++ program to find the shortest possible route // that visits every city exactly once and returns to // the starting point using backtracking
#include <bits/stdc++.h> using namespace std;
void totalCost(vector<vector> &cost, vector &visited, int currPos, int n, int count, int costSoFar, int &ans) {
// If all nodes are visited and there's an edge to
// start node
if (count == n && cost[currPos][0]) {
// Update the minimum cost
ans = min(ans, costSoFar + cost[currPos][0]);
return;
}
// Try visiting each node from current position
for (int i = 0; i < n; i++) {
if (!visited[i] && cost[currPos][i]) {
// If node not visited and has an edge
// Mark as visited
visited[i] = true;
totalCost(cost, visited, i, n, count + 1,
costSoFar + cost[currPos][i], ans);
visited[i] = false;
}
}}
int tsp(vector<vector> &cost) { int n = cost.size(); vector visited(n, false); visited[0] = true; int ans = INT_MAX; totalCost(cost, visited, 0, n, 1, 0, ans); return ans; } int main() {
vector<vector<int>> cost = {{0, 10, 15, 20},
{10, 0, 35, 25},
{15, 35, 0, 30},
{20, 25, 30, 0}};
int res = tsp(cost);
cout << res << endl;
return 0;}
Java
// Java program to find the shortest possible route // that visits every city exactly once and returns to // the starting point using backtracking
import java.util.Arrays;
class GfG {
static void totalCost(int[][] cost, boolean[] visited,
int currPos, int n, int count,
int costSoFar, int[] ans) {
// If all nodes are visited and there's an edge to
// start node
if (count == n && cost[currPos][0] != 0) {
ans[0] = Math.min(ans[0],
costSoFar + cost[currPos][0]);
return;
}
// Try visiting each node from the current position
for (int i = 0; i < n; i++) {
if (!visited[i] && cost[currPos][i] != 0) {
visited[i] = true;
totalCost(cost, visited, i, n, count + 1,
costSoFar + cost[currPos][i],
ans);
visited[i] = false;
}
}
}
static int tsp(int[][] cost) {
int n = cost.length;
boolean[] visited = new boolean[n];
Arrays.fill(
visited,
false);
visited[0] = true;
int[] ans = {
Integer.MAX_VALUE
};
totalCost(cost, visited, 0, n, 1, 0,
ans);
return ans[0];
}
public static void main(String[] args) {
int n = 4;
int[][] cost = { { 0, 10, 15, 20 },
{ 10, 0, 35, 25 },
{ 15, 35, 0, 30 },
{ 20, 25, 30, 0 } };
int res = tsp(cost);
System.out.println(res);
}}
Python
Python program to find the shortest possible route
that visits every city exactly once and returns to
the starting point using backtracking
def totalCost(cost, visited, currPos, n, count, costSoFar, ans):
# If all nodes are visited and there's an edge to the start node
if count == n and cost[currPos][0] != 0:
# Update the minimum cost
ans[0] = min(ans[0], costSoFar + cost[currPos][0])
return
# Try visiting each node from the current position
for i in range(n):
# If node not visited and has an edge
if not visited[i] and cost[currPos][i] != 0:
visited[i] = True
totalCost(cost, visited, i, n, count + 1,
costSoFar + cost[currPos][i], ans)
visited[i] = Falsedef tsp(cost): n = len(cost) visited = [False] * n visited[0] = True
# Use a list to store the minimum cost
# (to pass by reference)
ans = [float('inf')]
totalCost(cost, visited, 0, n, 1, 0, ans)
return ans[0]if name == "main": cost = [ [0, 10, 15, 20], [10, 0, 35, 25], [15, 35, 0, 30], [20, 25, 30, 0] ] res = tsp(cost) print(res)
C#
// C# program to find the shortest possible route // that visits every city exactly once and returns to // the starting point using backtracking
using System; using System.Collections.Generic;
class GfG { static void totalCost(List<List > cost, bool[] visited, int currPos, int n, int count, int costSoFar, ref int ans) {
// If all nodes are visited and there's an edge to
// the starting node
if (count == n && cost[currPos][0] != 0) {
// Update the minimum cost
ans = Math.Min(ans,
costSoFar + cost[currPos][0]);
return;
}
// Try visiting each node from the current position
for (int i = 0; i < n; i++) {
if (!visited[i] && cost[currPos][i] != 0) {
visited[i] = true;
totalCost(cost, visited, i, n, count + 1,
costSoFar + cost[currPos][i],
ref ans);
visited[i] = false;
}
}
}
static int tsp(List<List<int> > cost) {
int n = cost.Count;
bool[] visited = new bool[n];
visited[0] = true;
int ans
= int.MaxValue;
totalCost(cost, visited, 0, n, 1, 0, ref ans);
return ans;
}
static void Main() {
List<List<int> > cost = new List<List<int> >() {
new List<int>{ 0, 10, 15, 20 },
new List<int>{ 10, 0, 35, 25 },
new List<int>{ 15, 35, 0, 30 },
new List<int>{ 20, 25, 30, 0 }
};
int res= Tsp(cost);
Console.WriteLine(res);
}}
JavaScript
// JavaScript program to find the shortest possible route // that visits every city exactly once and returns to // the starting point using backtracking
function totalCost(cost, visited, currPos, n, count, costSoFar, ans) {
// If all nodes are visited and there's an edge to the
// starting node
if (count === n && cost[currPos][0] !== 0) {
// Update the minimum cost
ans[0] = Math.min(ans[0],
costSoFar + cost[currPos][0]);
return;
}
// Try visiting each node from the current position
for (let i = 0; i < n; i++) {
if (!visited[i]
&& cost[currPos][i]
!== 0) {
visited[i] = true;
totalCost(cost, visited, i, n, count + 1,
costSoFar + cost[currPos][i],
ans);
visited[i] = false;
}
}}
function tsp(cost) { const n = cost.length; const visited = new Array(n).fill( false); visited[0] = true;
let ans = [
Number.MAX_VALUE
];
totalCost(cost, visited, 0, n, 1, 0,
ans);
return ans[0];}
const cost = [ [ 0, 10, 15, 20 ], [ 10, 0, 35, 25 ], [ 15, 35, 0, 30 ], [ 20, 25, 30, 0 ] ];
const res = tsp(cost); console.log(res);
`
**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)