ℹ️ Select 'Choose Exercise', or randomize 'Next Random Exercise' in selected language.

Choose Exercise:
Timer 00:00
WPM --
Score --
Acc --
Correct chars --

Bitmask Optimization for Traveling Salesperson

C++

Goal -- WPM

Ready
Exercise Algorithm Area
1#include <vector>
2#include <algorithm>
3#include <limits>
4
5const int INF = std::numeric_limits<int>::max();
6
7int solveTSP(const std::vector<std::vector<int>>& dist) {
8int n = dist.size();
9if (n == 0) return 0;
10if (n == 1) return 0; // Single city, no travel cost.
11
12// dp[mask][i] = minimum cost to visit cities represented by mask, ending at city i.
13// Mask is a bitmask where the j-th bit is set if city j has been visited.
14std::vector<std::vector<int>> dp(1 << n, std::vector<int>(n, INF));
15
16// Base case: Starting at city 0, cost is 0.
17// The mask (1 << 0) means only city 0 is visited.
18dp[1][0] = 0;
19
20// Iterate through all possible masks (subsets of cities).
21// Start from mask 1 (only city 0 visited) up to (1 << n) - 1 (all cities visited).
22for (int mask = 1; mask < (1 << n); ++mask) {
23// Iterate through all cities 'i' that could be the last visited city in the current mask.
24for (int i = 0; i < n; ++i) {
25// Check if city 'i' is included in the current mask.
26if (mask & (1 << i)) {
27// Iterate through all possible previous cities 'j' that could have led to city 'i'.
28for (int j = 0; j < n; ++j) {
29// Check if city 'j' is in the mask AND is not the same as city 'i'.
30// Also, ensure that city 'j' was visited in the previous state (mask excluding city 'i').
31if ((mask & (1 << j)) && i != j) {
32int prevMask = mask ^ (1 << i); // Mask without city 'i'
33if (dp[prevMask][j] != INF) {
34dp[mask][i] = std::min(dp[mask][i], dp[prevMask][j] + dist[j][i]);
35}
36}
37}
38}
39}
40}
41
42// After filling DP table, find the minimum cost to return to the starting city (city 0)
43// from any city 'i' after visiting all other cities.
44int minTourCost = INF;
45int finalMask = (1 << n) - 1; // Mask representing all cities visited.
46for (int i = 1; i < n; ++i) {
47if (dp[finalMask][i] != INF) {
48minTourCost = std::min(minTourCost, dp[finalMask][i] + dist[i][0]);
49}
50}
51
52return (minTourCost == INF) ? -1 : minTourCost; // Return -1 if no tour is possible.
53}
Algorithm description viewbox

Bitmask Optimization for Traveling Salesperson

Algorithm description:

This C++ function solves the Traveling Salesperson Problem (TSP) for a small number of cities using dynamic programming with bitmasking. The state `dp[mask][i]` represents the minimum cost to visit the set of cities indicated by `mask`, ending at city `i`. The algorithm iterates through all possible subsets of cities and all possible ending cities, calculating the minimum cost to reach each state. Finally, it finds the minimum cost to complete the tour by returning to the starting city.

Algorithm explanation:

The `solveTSP` function uses dynamic programming with bitmasking to find the minimum cost tour. The state `dp[mask][i]` stores the minimum cost to visit cities represented by the bitmask `mask`, with the tour ending at city `i`. The base case is `dp[1][0] = 0`, meaning starting at city 0 with only city 0 visited costs 0. The algorithm iterates through all possible masks from 1 up to `(1 << n) - 1`. For each mask, it considers every city `i` present in the mask as the potential last city. It then iterates through all possible previous cities `j` (also in the mask, and `j != i`). The transition is `dp[mask][i] = min(dp[mask][i], dp[prevMask][j] + dist[j][i])`, where `prevMask` is `mask` with the `i`-th bit unset. This means the cost to reach `mask` ending at `i` is the cost to reach `prevMask` ending at `j`, plus the distance from `j` to `i`. After filling the DP table, the minimum tour cost is found by considering `dp[(1 << n) - 1][i] + dist[i][0]` for all `i` from 1 to `n-1`. The time complexity is O(n^2 * 2^n) due to the three nested loops (mask, current city, previous city). The space complexity is O(n * 2^n) for the DP table. Edge cases like 0 or 1 city are handled.

Pseudocode:

CONSTANT INF = infinity

FUNCTION solveTSP(dist):
  n = number of cities
  IF n == 0 THEN RETURN 0
  IF n == 1 THEN RETURN 0

  dp = 2D array of size (2^n) x n, initialized to INF
  dp[1][0] = 0 // Base case: start at city 0, mask = 1 (00...01)

  FOR mask FROM 1 TO (2^n - 1):
    FOR i FROM 0 TO n - 1: // Current city (end of path)
      IF i-th bit is SET in mask THEN
        FOR j FROM 0 TO n - 1: // Previous city
          IF j-th bit is SET in mask AND i != j THEN
            prevMask = mask XOR (1 << i) // Mask without city i
            IF dp[prevMask][j] != INF THEN
              dp[mask][i] = MIN(dp[mask][i], dp[prevMask][j] + dist[j][i])
            END IF
          END IF
        END FOR
      END IF
    END FOR
  END FOR

  minTourCost = INF
  finalMask = (2^n) - 1 // Mask with all bits set
  FOR i FROM 1 TO n - 1:
    IF dp[finalMask][i] != INF THEN
      minTourCost = MIN(minTourCost, dp[finalMask][i] + dist[i][0])
    END IF
  END FOR

  RETURN (minTourCost == INF) ? -1 : minTourCost
END FUNCTION