KatInterview

Minimum Cost to Visit All Booths at a Fair

Dynamic ProgrammingAuto-graded · 13 test cases
EasyAuto-gradedDynamic Programmingdynamic programmingbitmask DPgraphs

Last updated

Tests bitmask DP on small n by finding the minimum total travel cost to visit every booth at a fair, starting and ending at the entrance.

Minimum Cost to Visit All Booths at a Fair

You are helping plan a visit to a small fair. The fair has an entrance (always at position 0 in the list) and n booths, for a total of n + 1 locations indexed 0 through n.

You are given a 2-D list cost where cost[i][j] is the travel cost to go directly from location i to location j. Travel costs are not necessarily symmetric (cost[i][j] may differ from cost[j][i]).

Your goal is to find the minimum total cost of a route that:

  1. Starts at the entrance (location 0),
  2. Visits every booth (locations 1 through n) exactly once, and
  3. Returns to the entrance (location 0).

Return this minimum cost as an integer (all costs are non-negative integers).

Constraints

  • 1 ≤ n ≤ 12 (number of booths; total locations = n + 1, at most 13)
  • cost is a square matrix of size (n + 1) × (n + 1)
  • 0 ≤ cost[i][j] ≤ 1000 for all i, j
  • cost[i][i] = 0 for all i
  • It is always possible to complete the route (the graph is complete)
  • You must visit every booth exactly once before returning; skipping or revisiting a booth is not allowed

Examples

Example 1

Input: min_fair_tour_cost([[0, 10, 15, 20], [10, 0, 35, 25], [15, 35, 0, 30], [20, 25, 30, 0]])

Output: 80

Example 2

Input: min_fair_tour_cost([[0, 1, 2], [1, 0, 3], [2, 3, 0]])

Output: 6

Example 3

Input: min_fair_tour_cost([[0, 5], [5, 0]])

Output: 10

Hints

Hint 1

Let dp[mask][i] represent the minimum cost to reach booth i, having visited exactly the set of booths encoded in mask. Start with dp[1<<i][i] = cost[0][i] for each booth i.

Hint 2

Transition: for each state (mask, i), try extending to an unvisited booth j: dp[mask | (1<<j)][j] = min(..., dp[mask][i] + cost[i+1][j+1]). Use 0-indexed booth bits but be careful about the offset between bit positions and location indices.

Hint 3

The answer is the minimum over all booths i of dp[full_mask][i] + cost[i+1][0], where full_mask has all n booth bits set.