Cheapest Round-Trip Inspection Tour
Dynamic ProgrammingAuto-graded · 16 test casesLast 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 <= 150 <= cost[i][j] <= 1000cost[i][i] = 0for alli(no self-travel cost)- The matrix is not necessarily symmetric:
cost[i][j]may not equalcost[j][i] - The tour must start and end at facility
0and 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.
Worked solution
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This is the Asymmetric Traveling Salesman Problem (ATSP). The direction of travel matters, so we cannot simplify by assuming symmetric costs. With n ≤ 15, brute-force enumeration of all (n-1)! orderings reaches roughly 87 billion routes at n = 15 — far too slow. The right tool is the Held–Karp bitmask DP, which reduces the complexity to O(2^n · n^2).
Key Insight
The cost of optimally completing a partial tour depends on exactly two things:
- Which facilities have already been visited (encoded as a bitmask).
- Which facility the team is currently at.
The specific order in which the visited facilities were reached is irrelevant — only the set and the current position matter. This optimal-substructure property lets us define a clean recurrence.
State Definition
dp[mask][last] = minimum cost of a path that starts at facility 0,
visits exactly the facilities whose bits are set in mask,
and ends at facility last.
Base case: dp[1][0] = 0 — only facility 0 (bit 0 set) has been visited, and we are standing there at zero cost.
Transition: From state (mask, last), travel to any unvisited facility nxt (bit nxt not set in mask):
dp[mask | (1 << nxt)][nxt] = min(
dp[mask | (1 << nxt)][nxt],
dp[mask][last] + cost[last][nxt]
)
Answer: When mask = full = (1 << n) - 1, all facilities have been visited. The team must return home:
answer = min over last in 1..n-1 of ( dp[full][last] + cost[last][0] )
Why This Is Correct
- Optimal substructure. If the cheapest complete tour ends with leg
last → 0, the prefix ending atlastmust itself be the cheapest path visiting exactly the setfull \ {last}from 0. If it weren't, substituting a cheaper prefix would lower the total cost — a contradiction. - Evaluation order. Every transition strictly increases the number of set bits in
mask, so iterating masks in ascending numeric order ensures each state is fully settled before being used as a source. No memoization or recursion is needed. - Validity guarantees. Masks without bit 0 are skipped (the tour always starts at 0).
nxtis restricted to1..n-1, so facility 0 is never revisited mid-tour. The answer is read only from the fully-set mask, guaranteeing every facility is visited exactly once. - Asymmetric costs. Since we always index
cost[last][nxt](from → to), direction is respected automatically.
Complexity
- Time:
O(2^n · n^2)—2^nmasks ×nchoices oflast×nchoices ofnxt. Forn = 15this is about 7.4 million operations, which runs comfortably within time limits. - Space:
O(2^n · n)— the DP table. Forn = 15this is about 491,520 entries.
Edge Cases
n = 2: The only possible tour is0 → 1 → 0. The DP setsdp[0b11][1] = cost[0][1]and returnscost[0][1] + cost[1][0].- Asymmetric costs: Handled naturally by always indexing
cost[from][to]. - Zero-cost edges: Perfectly fine; infinity as the "unreached" sentinel is never confused with a real cost of 0.
- Self-loops
cost[i][i]: Never accessed, since a facility is never revisited.
Reference Solution
from typing import List
def min_inspection_tour_cost(cost: List[List[int]]) -> int:
n = len(cost)
full = (1 << n) - 1
# dp[mask][last]: min cost to start at 0, visit exactly the facilities
# whose bits are set in mask, and currently be at facility `last`.
dp = [[float('inf')] * n for _ in range(1 << n)]
dp[1][0] = 0 # only facility 0 visited, standing there at zero cost
for mask in range(1 << n):
if not (mask & 1): # every valid partial tour includes facility 0
continue
for last in range(n):
cur = dp[mask][last]
if cur == float('inf'):
continue
for nxt in range(1, n): # never re-enter facility 0 mid-tour
if not (mask & (1 << nxt)):
next_mask = mask | (1 << nxt)
candidate = cur + cost[last][nxt]
if candidate < dp[next_mask][nxt]:
dp[next_mask][nxt] = candidate
# Close the tour: return from the last facility visited back to facility 0
return min(dp[full][last] + cost[last][0] for last in range(1, n))