AlgoFrames

Bitmask DP: TSP and assignments

Bitmask DP uses the bits of an integer to record which items are used, solving the travelling salesperson and assignment problems for small n.

Before you start: State machine DP: stock problems.

The idea

One integer can store a whole set of visited cities. Bit k is 1 when city k has been visited.

Intuition

Three cities have eight subsets, so eight masks. Give each mask its own row in a table.

Cost depends on the set and on the city you stand in. Visiting 0, 1, 2 costs less than 0, 2, 1 here.

The order inside the set does not matter for what comes next. Only the visited set and the last city do, so one cell can stand for every order.

Adding a city turns on one bit, so the new mask is always bigger. Filling masks in increasing order fills every source cell first.

Complexity

There are 2^n masks, n last cities and n next cities: O(n² · 2^n) time. Trying every order costs n!.

The table holds n · 2^n numbers: O(n · 2^n) space. That limits this method to about 20 cities.

At 20 cities the table has 20 · 1,048,576 cells, about 21 million numbers. At 25 cities it is 32 times bigger.

Pitfalls

Test a bit as (mask & (1 << k)) != 0. Without the parentheses, == binds first and the test gives 0 even when the bit is set.

Start every cell at infinity, not 0. A 0 invents a free trip, and min then prefers it to every real one.

Variations

A round trip adds the way back to city 0 to each last cell of the full row. The answer is the smallest sum.

Assignment needs one value per mask. The number of set bits says which worker is next, so no last-city column is needed.

Counting valid subsets builds each mask from a smaller one. Mask 011 is invalid because items 0 and 1 conflict, so 111 is invalid too.

Code

Pseudocode

shortestTrip(dist):
  n ← number of cities,  full ← 2^n - 1
  dp[mask][last] ← ∞ for every mask and last
  dp[1][0] ← 0
  for mask ← 1 to full
    for last in mask
      if dp[mask][last] = ∞: skip
      for next not in mask
        dp[mask | 1 << next][next] ← min(itself, dp[mask][last] + dist[last][next])
  return min of dp[full][last] over last

Python

def shortest_trip(dist):
    n = len(dist)
    full = (1 << n) - 1
    INF = float("inf")
    dp = [[INF] * n for _ in range(full + 1)]
    dp[1][0] = 0
    for mask in range(1, full + 1, 2):
        for last in range(n):
            if dp[mask][last] == INF:
                continue
            for nxt in range(n):
                if mask & (1 << nxt):
                    continue
                nm = mask | (1 << nxt)
                dp[nm][nxt] = min(dp[nm][nxt], dp[mask][last] + dist[last][nxt])
    return min(dp[full])

JavaScript

function shortestTrip(dist) {
  const n = dist.length;
  const full = (1 << n) - 1;
  const dp = Array.from({ length: full + 1 }, () => new Array(n).fill(Infinity));
  dp[1][0] = 0;
  for (let mask = 1; mask <= full; mask += 2) {
    for (let last = 0; last < n; last++) {
      if (dp[mask][last] === Infinity) continue;
      for (let next = 0; next < n; next++) {
        if (mask & (1 << next)) continue;
        const nm = mask | (1 << next);
        dp[nm][next] = Math.min(dp[nm][next], dp[mask][last] + dist[last][next]);
      }
    }
  }
  return Math.min(...dp[full]);
}

Java

static int shortestTrip(int[][] dist) {
    int n = dist.length, full = (1 << n) - 1;
    int INF = Integer.MAX_VALUE / 2;
    int[][] dp = new int[full + 1][n];
    for (int[] row : dp) java.util.Arrays.fill(row, INF);
    dp[1][0] = 0;
    for (int mask = 1; mask <= full; mask += 2)
        for (int last = 0; last < n; last++) {
            if (dp[mask][last] >= INF) continue;
            for (int next = 0; next < n; next++) {
                if ((mask & (1 << next)) != 0) continue;
                int nm = mask | (1 << next);
                dp[nm][next] = Math.min(dp[nm][next], dp[mask][last] + dist[last][next]);
            }
        }
    return java.util.Arrays.stream(dp[full]).min().getAsInt();
}

Practice problems (5)

Which mask is it? Warm-up

Four cities are numbered 0 to 3. Bit k of a mask is 1 when city k is visited, and masks are written with bit 3 on the left. Pick the mask for "cities 0 and 2 are visited, cities 1 and 3 are not".

Fill the trip table Warm-up

Follow the trip table on three cities that start at city 0. Row labels are masks: bit k is 1 when city k is visited. Answer each question before the step plays.

Shortest path visiting all nodes Standard

graph[i] lists the neighbours of node i in a connected, undirected graph. You may start at any node, move along edges, and revisit nodes and edges as often as you like.

Return the fewest moves that visit every node at least once.

Minimum cost assignment Standard

costs[i][j] is the cost of giving task j to worker i. There are as many workers as tasks, and every worker gets exactly one task, with no task used twice.

Return the smallest possible total cost.

Count valid subsets Standard

There are n items numbered 0 to n - 1. Each pair in conflicts names two items that cannot be chosen together.

Count the subsets of items that contain no conflicting pair. The empty subset counts.

Related topics

Next on the path: Tree DP