Traveling Salesman (DP + Bitmask) - Problem

Given a weighted undirected graph with n cities (numbered 0 to n-1) and the distances between them, find the shortest route that visits all cities exactly once and returns to the starting city (city 0).

This is the classic Traveling Salesman Problem (TSP). Use dynamic programming with bitmask to track which cities have been visited.

The graph is represented as a 2D matrix where distances[i][j] is the distance between city i and city j. If there's no direct path, the distance is Integer.MAX_VALUE.

Note: The number of cities will be at most 20 to make the DP + bitmask approach feasible.

Input & Output

Example 1 — Basic 4-City TSP
$ Input: distances = [[0,10,15,20],[10,0,35,25],[15,35,0,30],[20,25,30,0]]
Output: 65
💡 Note: Optimal route: 0 → 1 → 3 → 2 → 0 with total cost 10 + 25 + 30 + 0 = 65, or 0 → 2 → 3 → 1 → 0 with cost 15 + 30 + 25 + (-5) = 65
Example 2 — Small Triangle
$ Input: distances = [[0,5,3],[5,0,4],[3,4,0]]
Output: 12
💡 Note: Only possible route: 0 → 2 → 1 → 0 with cost 3 + 4 + 5 = 12
Example 3 — Impossible Path
$ Input: distances = [[0,1,null],[1,0,null],[null,null,0]]
Output: -1
💡 Note: Cannot visit city 2 and return, as there are no paths to/from city 2

Constraints

  • 1 ≤ distances.length ≤ 20
  • distances[i][j] = distances[j][i] (symmetric)
  • distances[i][i] = 0
  • 0 ≤ distances[i][j] ≤ 106 or null (no path)

Visualization

Tap to expand
INPUTALGORITHMRESULTDistance Matrix (4 cities)0 10 15 2010 0 35 2515 35 0 3020 25 30 0Cities: 0,1,2,3Find shortest routevisiting all cities onceDP + Bitmask States1dp[0001][0] = 02dp[0011][1] = 103dp[0101][2] = 154dp[1111] final statesBitmask tracks visited1011₂ = cities 0,1,3Time: O(n² × 2ⁿ)Space: O(n × 2ⁿ)Optimal Tour FoundRoute: 0→1→3→2→0Cost: 10+25+30+0 = 650123Key Insight:Dynamic programming with bitmask reduces TSP from O(n!) brute force to O(n² × 2ⁿ) bystoring optimal solutions for each (visited_cities_set, current_city) state combination.TutorialsPoint - Traveling Salesman (DP + Bitmask) | Dynamic Programming
Asked in
Google 35 Amazon 28 Microsoft 22 Apple 18
25.0K Views
Medium Frequency
~35 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen