KatInterview

Cheapest Round-Trip Inspection Tour

Dynamic ProgrammingAuto-graded · 16 test cases
HardAuto-gradedDynamic Programmingbitmask-dptraveling-salesmangraphs

Last updated

Tests bitmask dynamic programming (Held–Karp) to find the minimum-cost Hamiltonian cycle in a small directed weighted graph.

Problem

A quality-control team must inspect a set of n facilities, numbered 0 through n-1. The team starts at facility 0, visits every other facility exactly once, and then returns to facility 0. Travel between facilities is one-way and direction-dependent: the cost to go from facility i to facility j is given by cost[i][j], which may differ from cost[j][i].

Given the n × n travel-cost matrix cost, return the minimum total travel cost needed to complete the full inspection tour.

Constraints

  • 2 <= n <= 15
  • 0 <= cost[i][j] <= 1000
  • cost[i][i] = 0 for all i (no self-travel cost)
  • The matrix is not necessarily symmetric: cost[i][j] may not equal cost[j][i]
  • The tour must start and end at facility 0 and visit every facility exactly once

Examples

Example 1

Input: min_inspection_tour_cost([[0, 10, 15, 20], [5, 0, 9, 10], [6, 13, 0, 12], [8, 8, 9, 0]])

Output: 35

Hints

Hint 1

With n ≤ 15, the number of facilities is small but the number of possible orderings (n-1)! is far too large to enumerate. Think about what information you actually need to extend a partial tour optimally — you don't need the full order, just which facilities have been visited and where you currently are.

Hint 2

Define a DP table indexed by two things: a bitmask representing the set of facilities already visited, and the index of the facility you are currently at. The recurrence extends the tour to any unvisited facility. Make sure bit 0 is always set, since the tour starts at facility 0.

Hint 3

Iterate over masks in increasing numeric order — this is valid because adding any new facility to the visited set strictly increases the mask value. After filling the table for the fully-visited mask, don't forget to add the return leg back to facility 0 when computing the final answer.