KatInterview

Minimum Cost to Visit All Checkpoints

Dynamic ProgrammingAuto-graded · 14 test cases
MediumAuto-gradedDynamic Programmingdynamic programmingbitmask DPgraphs

Last updated

Tests bitmask DP over a small set of checkpoints to find the minimum-cost path that visits every checkpoint exactly once, starting and ending at a fixed depot.

Minimum Cost to Visit All Checkpoints

A delivery robot starts and ends at a depot (always node 0). It must visit every checkpoint (nodes 1 through n) exactly once before returning to the depot. You are given the pairwise travel costs between all locations (the depot plus the n checkpoints) as a 2-D list.

Given that cost matrix, find the minimum total travel cost for the robot to complete this round-trip.

Details

  • There are n + 1 nodes in total: node 0 is the depot, nodes 1 … n are checkpoints.
  • cost[i][j] is the non-negative integer cost to travel directly from node i to node j.
  • Travel costs are not necessarily symmetric: cost[i][j] may differ from cost[j][i].
  • The robot must leave the depot, visit every checkpoint exactly once (in any order), and return to the depot.
  • Return the minimum total cost of such a tour.

Constraints

  • 1 ≤ n ≤ 15 (so there are at most 16 nodes including the depot)
  • cost is an (n+1) × (n+1) matrix of non-negative integers
  • cost[i][i] = 0 for all i
  • 0 ≤ cost[i][j] ≤ 10 000
  • There is always at least one checkpoint (n ≥ 1)

Examples

Example 1

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

Output: 80

Example 2

Input: min_cost_tour([[0, 1, 100], [100, 0, 1], [1, 100, 0]])

Output: 3

Example 3

Input: min_cost_tour([[0, 7], [7, 0]])

Output: 14

Hints

Hint 1

Let the state be (current_node, set_of_visited_checkpoints). How many distinct states are there when n ≤ 15?

Hint 2

Use a bitmask of n bits where bit k (0-indexed) represents whether checkpoint k+1 has been visited. The full mask (all bits set) means every checkpoint has been visited.

Hint 3

Initialize dp[1 << (c-1)][c] = cost[0][c] for each checkpoint c, then transition by extending the tour to an unvisited checkpoint; finally add the return cost cost[node][0].