Full answer
Problem
Given an n x n matrix dist of travel costs (not necessarily symmetric), return the minimum cost of a tour that starts at city 0, visits every city exactly once and returns to city 0.
Example: [[0,10,15,20],[10,0,35,25],[15,35,0,30],[20,25,30,0]] has a best tour of 80 (0, 1, 3, 2, 0).
Constraints: 1 <= n <= 16, costs from 1 to 1,000.
Brute force
Try all (n - 1)! orders of the other cities and sum each route: O(n!), about 1.3 * 10^12 for n = 16.
Optimal approach
Held-Karp:
dp[1][0] = 0(only city 0 visited, standing at 0); everything else infinity.- For every mask containing city 0, every end j in mask with a finite value, and every k not in mask: relax
dp[mask | 1 << k][k]withdp[mask][j] + dist[j][k]. - Answer:
min(dp[full][j] + dist[j][0])for j from 1 to n - 1.
Masks are processed in increasing numeric order, which guarantees that every subset is finished before any of its supersets (adding a bit always increases the number).
Why it works
The best way to finish a tour only depends on which cities are already visited and where you are now, not on the order they were visited in. So all partial paths with the same (mask, end) can be merged into one state that keeps the cheapest cost. There are 2^n * n such states, each extended in n ways. The cross-check against full permutation search confirms the result, including asymmetric costs.
Complexity
O(2^n * n^2) time and O(2^n * n) space. For n = 16 that is about 16.8 million transitions, which is fine in compiled languages and a few seconds in Python.
Code
import random
from itertools import permutations
def tsp(dist):
"""Shortest tour visiting every city once and returning to city 0 (Held-Karp).
dp[mask][j] = cheapest path from 0 covering `mask` and ending at j. O(2^n * n^2) time, O(2^n * n) space."""
n = len(dist)
if n == 1:
return 0
INF = float("inf")
full = 1 << n
dp = [[INF] * n for _ in range(full)]
dp[1][0] = 0
for mask in range(full):
if not mask & 1:
continue # every path starts at city 0
for j in range(n):
cur = dp[mask][j]
if cur == INF:
continue
for k in range(n):
if mask >> k & 1:
continue
nm = mask | 1 << k
if cur + dist[j][k] < dp[nm][k]:
dp[nm][k] = cur + dist[j][k]
return min(dp[full - 1][j] + dist[j][0] for j in range(1, n))
def brute(dist):
n = len(dist)
if n == 1:
return 0
best = float("inf")
for p in permutations(range(1, n)):
route = (0,) + p + (0,)
best = min(best, sum(dist[a][b] for a, b in zip(route, route[1:])))
return best
if __name__ == "__main__":
d = [[0, 10, 15, 20], [10, 0, 35, 25], [15, 35, 0, 30], [20, 25, 30, 0]]
assert tsp(d) == 80 # 0-1-3-2-0
assert tsp([[0]]) == 0 and tsp([[0, 3], [4, 0]]) == 7
rng = random.Random(99)
for _ in range(150):
n = rng.randint(1, 7)
m = [[0 if i == j else rng.randint(1, 20) for j in range(n)] for i in range(n)] # asymmetric is fine
assert tsp(m) == brute(m)
print("all tests passed")Save as b99_bitmask_dp_tsp.py and run python3 b99_bitmask_dp_tsp.py. It prints all tests passed (Python 3.13.5).
Edge cases
n = 1 (cost 0). n = 2 (there and back). Asymmetric costs (handled; the direction matters). Missing edges (use infinity and check the answer). n above about 20 (memory and time grow too fast; use heuristics or branch and bound).
Pattern
DP over subsets with a bitmask state. The same structure solves the shortest path visiting all nodes (BFS over (mask, node)), assignment problems with n <= 20, minimum cost to connect groups, and partitioning into k equal-sum subsets.
import random
from itertools import permutations
def tsp(dist):
"""Shortest tour visiting every city once and returning to city 0 (Held-Karp).
dp[mask][j] = cheapest path from 0 covering `mask` and ending at j. O(2^n * n^2) time, O(2^n * n) space."""
n = len(dist)
if n == 1:
return 0
INF = float("inf")
full = 1 << n
dp = [[INF] * n for _ in range(full)]
dp[1][0] = 0
for mask in range(full):
if not mask & 1:
continue # every path starts at city 0
for j in range(n):
cur = dp[mask][j]
if cur == INF:
continue
for k in range(n):
if mask >> k & 1:
continue
nm = mask | 1 << k
if cur + dist[j][k] < dp[nm][k]:
dp[nm][k] = cur + dist[j][k]
return min(dp[full - 1][j] + dist[j][0] for j in range(1, n))
def brute(dist):
n = len(dist)
if n == 1:
return 0
best = float("inf")
for p in permutations(range(1, n)):
route = (0,) + p + (0,)
best = min(best, sum(dist[a][b] for a, b in zip(route, route[1:])))
return best
if __name__ == "__main__":
d = [[0, 10, 15, 20], [10, 0, 35, 25], [15, 35, 0, 30], [20, 25, 30, 0]]
assert tsp(d) == 80 # 0-1-3-2-0
assert tsp([[0]]) == 0 and tsp([[0, 3], [4, 0]]) == 7
rng = random.Random(99)
for _ in range(150):
n = rng.randint(1, 7)
m = [[0 if i == j else rng.randint(1, 20) for j in range(n)] for i in range(n)] # asymmetric is fine
assert tsp(m) == brute(m)
print("all tests passed")Held-Karp with masks in increasing order, cross-checked against all permutations on random asymmetric matrices up to 7 cities.
Complexity
Time: O(2^n * n^2). Space: O(2^n * n). Exact TSP is NP-hard; this is the classic exponential but far better than O(n!) method.
By level
Fresher: Explains why trying all orders is too slow and describes the (mask, city) state with a small example. Follows the transitions with guidance.
Mid: Implements Held-Karp correctly, reconstructs the tour with parent pointers, and states the complexity. Applies masks to the visit-all-nodes BFS variant.
Senior: Discusses heuristics such as nearest neighbour with 2-opt, branch and bound, and solver tools for large instances. Estimates memory before choosing bitmask DP and explains where exact methods stop being practical.
Key points
- State = (visited mask, current city)
- Order inside the mask does not matter for the future
- Increasing mask order processes subsets first
- Add the return edge at the end
- O(2^n * n^2)
Common mistakes
- Using a mask without the start city bit
- Forgetting the return to city 0
- Iterating masks in an order where supersets come before subsets
- Trying this for n = 30
Follow-ups
- How would you rebuild the actual tour?
- How do you find the shortest path that visits all nodes without returning?
- What heuristics would you use for 1,000 cities?
Tips
- Explain why the order inside the mask does not matter
- Estimate the number of states before coding
- Mention practical limits on n
Evaluation rubric
- Correct state and transition
- Correct answer with the return edge
- Correct complexity
- Knows the limits