VOOZH about

URL: https://www.geeksforgeeks.org/dsa/bitmasking-dynamic-programming-set-2-tsp/

⇱ Bitmasking and Dynamic Programming | Travelling Salesman Problem - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Bitmasking and Dynamic Programming | Travelling Salesman Problem

Last Updated : 23 Jul, 2025

Given a 2D grid of characters representing a town where '*' represents the houses, 'x' represents the blockage, '.' represents the vacant street area and 'o' represents the starting position. The task is to determine the minimum distance to be moved to visit all the houses if possible otherwise return -1. We can only move to adjacent cells that share exactly 1 edge with the current cell and we can visit a house twice or more.

Prerequisites:

Examples:

Input:

👁 bitmasking---------and---------dynamic---------programming---------travelling---------salesman---------problem---------1

Output: 22

Input:

👁 bitmasking---------and---------dynamic---------programming---------travelling---------salesman---------problem---------2

Output: 12

Approach - Using BFS + BitMasking

If we treat each house as a node, the problem can be viewed as finding the minimum steps required to visit all nodes. In this problem, each house is a node in a graph, and we need to find the shortest path to visit all of them. The key challenge is that the same node (house) can be visited multiple times, but only if it allows us to visit more houses. Simply revisiting a node with the same number of visited houses is redundant.

Since we are working with a grid and the cost to move to an adjacent cell is always one, we can use BFS to find the shortest path. However, since we can move in all four directions, the same node might be revisited multiple times. This means we cannot simply use a visited array as in standard BFS. Instead, we need a way to uniquely represent each state.
To address this, we assign each house a unique houseId. Once we have the houseId, we can track house visits by setting the corresponding bits in a bitmask. The bitmask represents the set of visited houses, and the coordinates (x, y) track the current position. This allows us to mark each state uniquely. Revisiting a node is only valid if it results in a different set of visited houses.


Output
8

Time Complexity: O(2^totalHouse*n*m) where n and m are number of rows and columns of matrix and totalHouse is the number of house in matrix.
Auxilary Space: O(2^totalHouse*n*m)

Comment
Article Tags: