Algo-Sim › Advanced DP
Travelling Salesman (Held-Karp bitmask DP)
Hard · Advanced DP · step through it in Java, Python and C++ on your own input
Shortest cycle through every city. Bitmask DP over (visited set, current city) replaces the (n − 1)! orders with 2ⁿ·n states.
Problem
Given a distance matrix dist where dist[i][j] is the cost of travelling from city i to city j, return the cost of the cheapest round trip that starts at city 0, visits every other city exactly once and returns to city 0.
Constraints
- 1 ≤ n ≤ 16 cities (2ⁿ · n² must stay manageable)
- dist[i][i] = 0 and dist[i][j] ≥ 0
- Brute force tries (n − 1)! tours; Held-Karp is O(2ⁿ · n²)
Edge cases to test
- One city: cost 0
- Two cities: there and back
- An unreachable pair (infinite cost)
Follow-up questions
- What is the cost of the bitmask DP?
- O(2ⁿ · n²) time and O(2ⁿ · n) memory: fine up to about n = 20.
- What do you do for large n?
- Heuristics: nearest neighbour, 2-opt improvements, or Christofides’ 1.5-approximation when distances satisfy the triangle inequality.
Solution
Java
public int shortestTour(int[][] dist) {
int n = dist.length, full = (1 << n) - 1, INF = Integer.MAX_VALUE / 2;
int[][] dp = new int[1 << n][n];
for (int[] row : dp) Arrays.fill(row, INF);
dp[1][0] = 0;
for (int mask = 3; mask <= full; mask += 2) { // odd masks contain city 0
for (int j = 1; j < n; j++) {
if ((mask & (1 << j)) == 0) continue;
int prev = mask ^ (1 << j);
for (int i = 0; i < n; i++)
if ((prev & (1 << i)) != 0 && dp[prev][i] < INF)
dp[mask][j] = Math.min(dp[mask][j], dp[prev][i] + dist[i][j]);
}
}
if (n == 1) return 0;
int best = INF;
for (int j = 1; j < n; j++) best = Math.min(best, dp[full][j] + dist[j][0]);
return best;
}Python
def shortest_tour(dist):
n = len(dist)
full = (1 << n) - 1
INF = float('inf')
dp = [[INF] * n for _ in range(1 << n)]
dp[1][0] = 0
for mask in range(3, full + 1, 2): # odd masks contain city 0
for j in range(1, n):
if not mask >> j & 1:
continue
prev = mask ^ (1 << j)
for i in range(n):
if prev >> i & 1 and dp[prev][i] < INF:
dp[mask][j] = min(dp[mask][j], dp[prev][i] + dist[i][j])
if n == 1:
return 0
best = min(dp[full][j] + dist[j][0] for j in range(1, n))
return bestC++
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int shortestTour(vector<vector<int>> &dist) {
int n = int(dist.size()), full = (1 << n) - 1, INF = INT_MAX / 2;
vector<vector<int>> dp = vector<vector<int>>(1 << n, vector<int>(n));
for (vector<int> &row : dp)
fill(row.begin(), row.end(), INF);
dp[1][0] = 0;
for (int mask = 3; mask <= full; mask += 2) { // odd masks contain city 0
for (int j = 1; j < n; j++) {
if ((mask & (1 << j)) == 0)
continue;
int prev = mask ^ (1 << j);
for (int i = 0; i < n; i++)
if ((prev & (1 << i)) != 0 && dp[prev][i] < INF)
dp[mask][j] = std::min(dp[mask][j], dp[prev][i] + dist[i][j]);
}
}
if (n == 1)
return 0;
int best = INF;
for (int j = 1; j < n; j++)
best = std::min(best, dp[full][j] + dist[j][0]);
return best;
}
};
More Advanced DP problems
- Burst Balloons (Hard)
- Partition to K Equal Sum Subsets (Medium)
- House Robber III (Medium)
- Longest Increasing Path in a Matrix (Hard)
- Regular Expression Matching (Hard)
- Wildcard Matching (Hard)
- Best Time to Buy and Sell Stock IV (Hard)