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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code