Skip to problem
←

Travelling Salesman

Hard 0 attempts

Given a square cost matrix dist, find the minimum-cost tour that visits every city exactly once and returns to its starting city.

dist[i][j] is the cost of traveling directly from city i to city j. Costs may be asymmetric, and every directed trip between different cities is available. Include the final return trip in the total.

You may fix city 0 as the starting point: any tour can be rotated to start there without changing its cost. Return only the minimum total cost, not the route. A single city requires no travel and returns 0.

Function contract

Implement tsp(dist).

Output: Return the minimum total cost of a tour that visits each city once and returns to its start. For one city, return 0.

Example 1

Input
dist = [[0,10,15,20],[10,0,35,25],[15,35,0,30],[20,25,30,0]]
Output
80

Example 2

Input
dist = [[0,5],[5,0]]
Output
10
Constraints
  • 1 <= dist.length <= 20
  • dist is square with diagonal entries 0.
  • Off-diagonal distances are integers in [1,10^4].
  • dist[i][j] need not equal dist[j][i]; every directed trip is available

Bitmask Dynamic Programming

Fix city 0 as the start. A mask records visited cities 1 through n - 1, and dp[mask, u] records the cheapest path ending at city u + 1. Extend each reachable state to every unvisited city. Once all cities have been visited, add the cost of returning to city 0.

Use one flat typed array instead of an array for every subset. Excluding city 0 from the mask halves the subset count; the table occupies about 40 MB at n = 20. Unreachable states use a sentinel larger than any possible tour cost.

javascript
function tsp(dist) {
  const n = dist.length;
  if (n === 1) return 0;
  const m = n - 1, states = 1 << m, all = states - 1;
  const infinity = 0xffffffff;
  const dp = new Uint32Array(states * m);
  dp.fill(infinity);
  for (let u = 0; u < m; u++) dp[(1 << u) * m + u] = dist[0][u + 1];
  for (let mask = 1; mask < states; mask++) {
    for (let ends = mask; ends; ends &= ends - 1) {
      const u = 31 - Math.clz32(ends & -ends);
      const cost = dp[mask * m + u];
      if (cost === infinity) continue;
      for (let remaining = all ^ mask; remaining; remaining &= remaining - 1) {
        const bit = remaining & -remaining;
        const v = 31 - Math.clz32(bit);
        const index = (mask | bit) * m + v;
        const next = cost + dist[u + 1][v + 1];
        if (next < dp[index]) dp[index] = next;
      }
    }
  }
  let answer = infinity;
  for (let u = 0; u < m; u++) {
    answer = Math.min(answer, dp[all * m + u] + dist[u + 1][0]);
  }
  return answer;
}

Time: O(2^n × n²). Space: O(2^n × n).

Loading discussion…

Saved in this browser only. Private to you.

JavaScript