Reading history

Bitmask DP and the Travelling Salesman Problem in C

7 min read 1 views

Learn bitmask dynamic programming in C: sets as bits, listing subsets, and solving the travelling salesman problem with Held-Karp.

A salesperson must visit every city once and return home, travelling as few kilometres as possible. This is the travelling salesman problem (TSP). Trying every order takes (n – 1)! steps, which explodes quickly: 15 cities already give over 87 billion orders. Bitmask dynamic programming does much better by storing the set of visited cities as the bits of a single number. This lesson first shows how bitmasks represent sets, then solves TSP with the Held-Karp algorithm in O(2n × n2) time.

In this lesson you will learn

  • Representing a set as the bits of an integer
  • Adding, removing and testing items with bitwise operators
  • Listing every subset by counting from 0 to 2n – 1
  • The DP state dp[mask][j] for TSP
  • Rebuilding the best route from parent pointers

You should know dynamic programming and bit manipulation.

Sets as Bitmasks

#include <stdio.h>

/* Bitmask basics: a set of up to 32 items stored in one int.
   Bit i is 1 when item i is in the set. */
void printSet(const char *label, unsigned mask, const char *names[], int n) {
    printf("%-18s {", label);
    int first = 1;
    for (int i = 0; i < n; i++)
        if (mask & (1u << i)) { printf(first ? "%s" : ", %s", names[i]); first = 0; }
    printf("}\n");
}

int main(void) {
    const char *city[] = { "Dhaka", "Sylhet", "Khulna", "Rajshahi" };
    unsigned visited = 0;
    visited |= 1u << 0;                 /* add Dhaka  */
    visited |= 1u << 2;                 /* add Khulna */
    printSet("visited:", visited, city, 4);
    printf("Sylhet visited? %s\n", (visited & (1u << 1)) ? "yes" : "no");
    visited &= ~(1u << 0);              /* remove Dhaka */
    printSet("after removing:", visited, city, 4);

    unsigned all = (1u << 4) - 1;       /* 1111 = every city */
    printSet("all cities:", all, city, 4);
    printSet("not yet visited:", all & ~visited, city, 4);

    /* Every subset of 3 items is a number from 0 to 7 */
    const char *fruit[] = { "mango", "jackfruit", "litchi" };
    printf("All %d subsets of 3 fruits:\n", 1 << 3);
    for (unsigned m = 0; m < (1u << 3); m++) {
        char label[16];
        snprintf(label, sizeof label, "  %u%u%u =", (m >> 2) & 1, (m >> 1) & 1, m & 1);
        printSet(label, m, fruit, 3);
    }
    return 0;
}

Output

visited:           {Dhaka, Khulna}
Sylhet visited? no
after removing:    {Khulna}
all cities:        {Dhaka, Sylhet, Khulna, Rajshahi}
not yet visited:   {Dhaka, Sylhet, Rajshahi}
All 8 subsets of 3 fruits:
  000 =            {}
  001 =            {mango}
  010 =            {jackfruit}
  011 =            {mango, jackfruit}
  100 =            {litchi}
  101 =            {mango, litchi}
  110 =            {jackfruit, litchi}
  111 =            {mango, jackfruit, litchi}
  • Bit i of the mask is 1 when item i is in the set. With 4 cities, the mask 0101 means cities 0 and 2.
  • mask | (1u << i) adds item i; mask & ~(1u << i) removes it; mask & (1u << i) tests it.
  • (1u << n) - 1 has all n bits set: the full set. all & ~visited gives the items not yet visited.
  • Counting from 0 to 2n – 1 lists every subset exactly once, because each number has a different pattern of bits.

The Travelling Salesman with Bitmask DP

#include <stdio.h>
#include <string.h>

#define N 5
#define INF 1000000000

/* Travelling salesman with bitmask DP (Held-Karp).
   dp[mask][j] = shortest route that starts at city 0, visits exactly the
   cities in mask, and ends at city j. */
const char *name[N] = { "Dhaka", "Cumilla", "Chattogram", "Sylhet", "Mymensingh" };
int dist[N][N] = {          /* example distances in km, rounded for practice */
    {   0,  97, 253, 240, 120 },
    {  97,   0, 155, 220, 190 },
    { 253, 155,   0, 330, 370 },
    { 240, 220, 330,   0, 240 },
    { 120, 190, 370, 240,   0 },
};
int dp[1 << N][N], parent[1 << N][N];

int main(void) {
    for (int m = 0; m < (1 << N); m++)
        for (int j = 0; j < N; j++) dp[m][j] = INF;
    dp[1][0] = 0;                                   /* only city 0 visited, standing at 0 */

    for (int mask = 1; mask < (1 << N); mask++) {
        if (!(mask & 1)) continue;                  /* every route starts at city 0 */
        for (int j = 0; j < N; j++) {
            if (dp[mask][j] == INF || !(mask & (1 << j))) continue;
            for (int k = 0; k < N; k++) {           /* extend the route to city k */
                if (mask & (1 << k)) continue;
                int next = mask | (1 << k), cost = dp[mask][j] + dist[j][k];
                if (cost < dp[next][k]) { dp[next][k] = cost; parent[next][k] = j; }
            }
        }
    }

    int full = (1 << N) - 1, best = INF, last = 0;
    for (int j = 1; j < N; j++)                     /* close the loop back to city 0 */
        if (dp[full][j] + dist[j][0] < best) { best = dp[full][j] + dist[j][0]; last = j; }

    int route[N], mask = full, j = last;
    for (int i = N - 1; i >= 0; i--) {              /* walk the parents backwards */
        route[i] = j;
        int pj = parent[mask][j];
        mask &= ~(1 << j);
        j = pj;
    }
    printf("Shortest tour: %d km\n", best);
    for (int i = 0; i < N; i++) printf("%s -> ", name[route[i]]);
    printf("%s\n", name[0]);
    printf("States: %d masks x %d cities = %d (brute force checks %d orders)\n",
           1 << N, N, (1 << N) * N, 24);
    return 0;
}

Output

Shortest tour: 942 km
Dhaka -> Mymensingh -> Sylhet -> Chattogram -> Cumilla -> Dhaka
States: 32 masks x 5 cities = 160 (brute force checks 24 orders)
  • State: dp[mask][j] is the shortest route that starts at city 0, visits exactly the cities in mask and ends at city j.
  • Start: dp[1][0] = 0. Only city 0 is visited and we are standing there.
  • Transition: from dp[mask][j], move to any unvisited city k: the new state is dp[mask | (1 << k)][k] with cost dist[j][k] added.
  • Masks are processed in increasing order. Adding a city always makes the mask larger, so every state is final before it is used.
  • Answer: with all cities visited, add the trip from the last city back home and take the smallest total.
  • parent[mask][j] remembers the previous city. Walking back from the end and removing each city from the mask rebuilds the route.
  • The key idea: the best way to finish depends only on which cities are done and where you are, not the order you visited them in. That turns a search over orders into a table over sets.
Cities (n)Brute force (n – 1)!Bitmask DP 2n × n2
524800
10362,880102,400
15about 87 billionabout 7.4 million
20about 1.2 × 1017about 419 million

For very small n brute force is cheaper, but the DP wins quickly. Beyond about 20 to 25 cities, memory for 2n × n states becomes the limit, and real route planners use approximation methods instead.

Common Mistakes

  1. Writing 1 << n with n of 31 or more on a 32-bit int, which overflows. Use 1u or 1ull.
  2. Forgetting operator precedence: mask & 1 << j == 0 does not mean what it looks like. Add brackets.
  3. Not fixing a start city, which repeats the same tour n times with different starting points.
  4. Using INF values that overflow when a distance is added to them.

Practice Exercises

Exercise 1. Write a loop that counts how many items are in a set stored as a mask.

Show answer
int count = 0;
for (unsigned m = mask; m; m &= m - 1) count++;   /* each step clears the lowest 1 bit */

GCC and Clang also offer __builtin_popcount(mask).

Exercise 2. How much memory does int dp[1 << 20][20] need?

Show answer

220 × 20 = 20,971,520 integers. At 4 bytes each, that is about 84 MB, so it should be allocated with malloc, not on the stack.

Frequently Asked Questions

Is there a fast exact algorithm for TSP?

No known algorithm solves every TSP instance in polynomial time; it is an NP-hard problem, as explained in P, NP and NP-hard. Held-Karp is exponential, but far better than trying every order.

Where else is bitmask DP used?

Any problem that tracks a small set of used items: assigning n workers to n jobs, covering all required skills with the fewest people, or visiting all checkpoints in a game map.

Summary

  • A bitmask stores a set of up to 32 or 64 items in one integer.
  • Bitwise OR, AND and NOT add, test and remove items in O(1).
  • dp[mask][j] stores the best route over a set of cities ending at j.
  • Held-Karp solves TSP in O(2n × n2), practical for about 20 cities.

Next: A* Search Algorithm in C.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *