KatInterview

Optimal Closed Tour Cost Across Directed Locations

Dynamic ProgrammingAuto-graded · 20 test cases
MediumAuto-gradedDynamic Programmingdynamic-programmingbit manipulationgraph

Last updated

Find the minimum cost to complete a full circuit starting and ending at node 0, visiting all other nodes exactly once with asymmetric leg costs.

You are managing a delivery vehicle that must complete a full route servicing $n$ distinct locations, indexed from $0$ to $n - 1$.

You are given a 2D integer array dist of size $n \times n$, where dist[i][j] represents the cost of traveling directly from location $i$ to location $j$. Travel costs can be directional (i.e., dist[i][j] may not be equal to dist[j][i]).

The route must:

  1. Begin at location $0$.
  2. Visit every other location ($1$ through $n - 1$) exactly once.
  3. Return to location $0$.

Return the minimum total cost required to complete such a full circuit. If $n = 1$, the route starts and ends at location $0$ without moving, so the cost is $0$.

Constraints

  • $1 \le n \le 16$
  • len(dist) == n and len(dist[i]) == n for all $0 \le i < n$
  • dist[i][i] == 0 for all $0 \le i < n$
  • $0 \le \text{dist}[i][j] \le 10^6$ for all $0 \le i, j < n$

Examples

Example 1

Input: min_tour_cost([[0, 3, 7, 4], [3, 0, 2, 6], [7, 2, 0, 5], [4, 6, 5, 0]])

Output: 14

Example 2

Input: min_tour_cost([[0, 1, 10], [10, 0, 1], [1, 10, 0]])

Output: 3

Example 3

Input: min_tour_cost([[0]])

Output: 0

Hints

Hint 1

The constraints on $n$ ($n \le 16$) suggest that an $O(n!)$ search is too slow, but an exponential dynamic programming approach using bitmasks will work.

Hint 2

Define state as `(mask, last_node)`, where `mask` is a bitfield representing the set of visited locations (excluding location 0), and `last_node` is the most recently visited location.

Hint 3

Iterate through masks in increasing order to ensure subproblems are solved before they are used to compute larger states, then find the minimum cost over all valid last nodes plus the cost to return to location 0.