Skip to content

feat: Add Bitmask DP TSP implementation - #7505

Open
YashKumar-404 wants to merge 5 commits into
TheAlgorithms:masterfrom
YashKumar-404:master
Open

feat: Add Bitmask DP TSP implementation#7505
YashKumar-404 wants to merge 5 commits into
TheAlgorithms:masterfrom
YashKumar-404:master

Conversation

@YashKumar-404

@YashKumar-404 YashKumar-404 commented Jul 1, 2026

Copy link
Copy Markdown

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

@codecov-commenter

codecov-commenter commented Jul 1, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 0% with 22 lines in your changes missing coverage. Please review.
✅ Project coverage is 80.59%. Comparing base (0a6c756) to head (1eb56ee).

Files with missing lines Patch % Lines
...om/thealgorithms/dynamicprogramming/BitmaskDP.java 0.00% 22 Missing ⚠️
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.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@DenizAltunkapan DenizAltunkapan left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the PR! The TSP logic looks correct, but a few things should be fixed before this can be merged:

  1. Add a test class. New algorithms need a BitmaskDPTest.java under src/test/.... Right now there is no test, so the code is not covered.
  2. Remove BitmaskDP_README.md from src/main/java. Source folders should only contain .java files. Please move the explanation into the class Javadoc instead.
  3. Return type / empty input. tsp returns int and uses Integer.MAX_VALUE. For n == 1 or disconnected costs the sum can overflow. Please guard against this (e.g. skip unreachable states) and document the expected input.
  4. Naming. distance is fine, but please make the class name match the algorithm (e.g. keep BitmaskDP only 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.

@github-actions

github-actions Bot commented Aug 2, 2026

Copy link
Copy Markdown

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!

@github-actions github-actions Bot added stale and removed stale labels Aug 2, 2026
@github-actions

github-actions Bot commented Sep 5, 2026

Copy link
Copy Markdown

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!

@github-actions github-actions Bot added the stale label Sep 5, 2026
Copilot AI lite review requested due to automatic review settings September 6, 2026 03:13

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 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.

Comment on lines +26 to +31
int n = distance.length;
if (n == 0) {
return 0;
}

int totalSubsets = 1 << n;
Comment on lines +20 to +25
/**
* 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) {
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

ADD BITWISE DP / SOS DP

5 participants