Travelling Salesman Problem
Pattern: Bitmask DP
Visit every city once and return to the start for the least cost. dp[mask][v] is the cheapest path that starts at city 0, visits exactly the cities in mask, and ends at v.
The problem
Given a matrix cost where cost[i][j] is the cost from city i to city j, return the least cost of a tour that starts at city 0, visits every city exactly once and returns to city 0.
Think first
- What must you remember about a partial tour?
- How can a set of cities be stored?
- How many states are there?
Hints
Brute force, and why it fails
Try every order: (n - 1)!.
The key insight
Different orders reaching the same set and city are merged into one state.
Dry run
Two cities, costs 0→1 = 111 and 1→0 = 112.
Step 1 of 2
The plan
dp[1][0] = 0
for mask, v in mask, w not in mask: dp[mask | 1 << w][w] = min(..., dp[mask][v] + cost[v][w])
return min over v of dp[full][v] + cost[v][0]
Complexity
- Time
O(2ⁿ × n²)- Space
O(2ⁿ × n)
Feasible up to about n = 20.
Edge cases
- One city: 0.
- Two cities.
- Asymmetric costs.
I've built my logic, show the code
Java
import java.util.*;
class Solution {
public int total_cost(int[][] cost) {
int n = cost.length, full = 1 << n;
final int INF = Integer.MAX_VALUE / 2;
int[][] dp = new int[full][n]; // dp[mask][v]: cheapest path from 0 visiting exactly mask, ending at v
for (int[] row : dp) Arrays.fill(row, INF);
dp[1][0] = 0;
for (int mask = 1; mask < full; mask++)
for (int v = 0; v < n; v++) {
if (dp[mask][v] == INF) continue;
for (int w = 0; w < n; w++) { // go on to a city not yet visited
if ((mask >> w & 1) == 1) continue;
int next = mask | (1 << w);
dp[next][w] = Math.min(dp[next][w], dp[mask][v] + cost[v][w]);
}
}
int best = n == 1 ? 0 : INF;
for (int v = 1; v < n; v++) best = Math.min(best, dp[full - 1][v] + cost[v][0]); // return home
return best;
}
}C++
class Solution {
public:
int total_cost(vector<vector<int>>& cost) {
int n = static_cast<int>(cost.size()), full = 1 << n;
const int INF = INT_MAX / 2;
vector<vector<int>> dp(full, vector<int>(n, INF)); // cheapest path from 0 visiting exactly mask, ending at v
dp[1][0] = 0;
for (int mask = 1; mask < full; mask++)
for (int v = 0; v < n; v++) {
if (dp[mask][v] == INF) continue;
for (int w = 0; w < n; w++) { // go on to a city not yet visited
if (mask >> w & 1) continue;
int next = mask | (1 << w);
dp[next][w] = min(dp[next][w], dp[mask][v] + cost[v][w]);
}
}
int best = n == 1 ? 0 : INF;
for (int v = 1; v < n; v++) best = min(best, dp[full - 1][v] + cost[v][0]); // return home
return best;
}
};Python
class Solution:
def total_cost(self, cost: list[list[int]]) -> int:
n = len(cost)
full, INF = 1 << n, float("inf")
dp = [[INF] * n for _ in range(full)] # dp[mask][v]: cheapest path from 0 visiting exactly mask, ending at v
dp[1][0] = 0
for mask in range(1, full):
for v in range(n):
if dp[mask][v] == INF:
continue
for w in range(n): # go on to a city not yet visited
if not mask >> w & 1:
nxt = mask | 1 << w
dp[nxt][w] = min(dp[nxt][w], dp[mask][v] + cost[v][w])
if n == 1:
return 0
return min(dp[full - 1][v] + cost[v][0] for v in range(1, n)) # return homeCommon mistakes
- Forgetting the return to city 0.
- Starting from every city (it is a cycle, so one start is enough).