Skip to content

feat: Add Bitmask DP TSP implementation#7505

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

feat: Add Bitmask DP TSP implementation#7505
YashKumar-404 wants to merge 4 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.16%. Comparing base (12aab70) to head (fe27f6a).

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.23%   80.16%   -0.07%     
+ Complexity     7354     7352       -2     
============================================
  Files           810      811       +1     
  Lines         23785    23807      +22     
  Branches       4678     4686       +8     
============================================
+ Hits          19083    19084       +1     
- Misses         3942     3963      +21     
  Partials        760      760              

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

ADD BITWISE DP / SOS DP

4 participants