feat: Add Bitmask DP TSP implementation - #7505
Conversation
Codecov Report❌ Patch coverage is
Additional details and impacted files@@ Coverage Diff @@
## master #7505 +/- ##
============================================
- Coverage 80.68% 80.59% -0.09%
+ Complexity 7529 7526 -3
============================================
Files 817 818 +1
Lines 24162 24184 +22
Branches 4759 4767 +8
============================================
- Hits 19494 19490 -4
- Misses 3906 3929 +23
- Partials 762 765 +3 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
DenizAltunkapan
left a comment
There was a problem hiding this comment.
Thanks for the PR! The TSP logic looks correct, but a few things should be fixed before this can be merged:
- Add a test class. New algorithms need a
BitmaskDPTest.javaundersrc/test/.... Right now there is no test, so the code is not covered. - Remove
BitmaskDP_README.mdfromsrc/main/java. Source folders should only contain.javafiles. Please move the explanation into the class Javadoc instead. - Return type / empty input.
tspreturnsintand usesInteger.MAX_VALUE. Forn == 1or disconnected costs the sum can overflow. Please guard against this (e.g. skip unreachable states) and document the expected input. - Naming.
distanceis fine, but please make the class name match the algorithm (e.g. keepBitmaskDPonly if it stays generic; since it only does TSP, a clearer name or a note in the Javadoc would help).
Also note the repo already has graph/TravelingSalesman.java — please mention in the description why this DP version is a useful addition.
|
This pull request has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contribution! |
|
This pull request has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contribution! |
There was a problem hiding this comment.
🟡 Changes recommended
The new TSP implementation has correctness issues around unreachable states/edges and single-node cases, and it’s missing the tests referenced in the PR description.
Once you've addressed the issues Copilot identified, you can request another Copilot review.
Pull request overview
Adds a Bitmask Dynamic Programming (Held–Karp) implementation for the Traveling Salesperson Problem (TSP) under the dynamicprogramming package, aligning with Issue #7503’s request for subset/bitmask DP examples.
Changes:
- Introduces
BitmaskDP.tsp(int[][])to compute the minimum TSP tour cost via bitmask DP. - Adds an accompanying Markdown document explaining the DP state, transitions, and final aggregation.
File summaries
| File | Description |
|---|---|
| src/main/java/com/thealgorithms/dynamicprogramming/BitmaskDP.java | New bitmask DP TSP implementation (currently needs input/edge handling fixes and tests). |
| src/main/java/com/thealgorithms/dynamicprogramming/BitmaskDP_README.md | Detailed explanation of the implementation and bitmask DP concepts. |
Review details
Suppressed comments (2)
src/main/java/com/thealgorithms/dynamicprogramming/BitmaskDP.java:56
- The transition step treats Integer.MAX_VALUE edges as a valid cost. Adding Integer.MAX_VALUE will overflow to a negative number and can incorrectly become the new minimum. Skip transitions where distance[u][v] is Integer.MAX_VALUE (no edge), consistent with the existing TravelingSalesman.dynamicProgramming implementation.
for (int v = 0; v < n; v++) {
// If node 'v' IS already in the subset, skip
if ((mask & (1 << v)) != 0) {
continue;
}
src/main/java/com/thealgorithms/dynamicprogramming/BitmaskDP.java:70
- Final tour computation can overflow when dp[allVisitedMask][i] is Integer.MAX_VALUE (unreachable) or when the return edge is Integer.MAX_VALUE, producing a negative minCost. Guard against unreachable states/edges and return 0 when no tour exists, matching com.thealgorithms.graph.TravelingSalesman.dynamicProgramming behavior.
// Find the minimum cost to return to the starting node (0) from the last visited node
int minCost = Integer.MAX_VALUE;
int allVisitedMask = totalSubsets - 1; // All n bits are 1
for (int i = 1; i < n; i++) {
- Files reviewed: 2/2 changed files
- Comments generated: 2
- Review effort level: Lite
💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.
| int n = distance.length; | ||
| if (n == 0) { | ||
| return 0; | ||
| } | ||
|
|
||
| int totalSubsets = 1 << n; |
| /** | ||
| * Solves the Traveling Salesperson Problem using Bitmask DP. | ||
| * @param distance A 2D array where distance[i][j] is the cost to travel from node i to node j. | ||
| * @return The minimum distance to visit all nodes and return to the start. | ||
| */ | ||
| public static int tsp(int[][] distance) { |
Bitmask Dynamic Programming: Traveling Salesperson Problem (TSP)
Overview
This implementation demonstrates how to use Bitmask Dynamic Programming to solve the Traveling Salesperson Problem (TSP).
The Traveling Salesperson Problem asks: "Given a list of cities and the distances between each pair of cities, what is the shortest possible route that visits each city exactly once and returns to the origin city?"
What is Bitmask DP?
When solving optimization problems that involve subsets or combinations of elements (where the order/inclusion matters), tracking the "visited" state using standard arrays or objects can be highly inefficient.
Bitmask DP optimizes this by representing a subset of elements as bits in an integer:
If the$i$ -th bit is 1, the $i$ -th element is included in the subset.
If the$i$ -th bit is 0, the $i$ -th element is excluded.
Core Bitwise Operations Used:
Add an element to the subset: mask | (1 << i)
Check if an element is in the subset: (mask & (1 << i)) != 0
Because an integer is typically 32 bits, this technique is incredibly fast and memory-efficient but is generally restricted to problem sizes where$N \le 20$ .
Algorithm Complexity
For a graph with$N$ vertices:
Time Complexity:$O(N^2 \cdot 2^N)$
There are$2^N$ possible subsets. For each subset, we iterate through $N$ currently visited nodes, and for each, we try to visit $N$ unvisited nodes. This is a massive improvement over the naive $O(N!)$ brute-force approach.
Space Complexity:$O(N \cdot 2^N)$
We use a 2D array dp[1 << N][N] to store the minimum cost for each subset and ending node.
Example
If we have 4 cities (0, 1, 2, 3), a subset containing cities 0, 2, and 3 is represented by the binary number 1101 (which is the integer 13).
The DP state dp[13][2] stores the minimum distance traveled to visit cities {0, 2, 3} where the last visited city is 2.
Transitions are made by checking unvisited cities (like city 1), adding them to the mask (1101 | 0010 = 1111), and updating the minimum cost.
How to Run & Test
If you have cloned the repository locally, you can run the JUnit tests for this specific implementation using Maven:
mvn test -Dtest=BitmaskDPTest
Resolves #7503