Back to challenges
Hard 0 solved 0% acceptance

Shortest Delivery Tour

Visit every city once and return home as cheaply as possible.

What you'll learn

  • Store visited cities as bits
  • Write a DP over subsets and last city
  • Solve small TSP instances exactly

Problem

A courier starts at city 0, visits every other city exactly once and returns to city 0. distances[i][j] is the cost from i to j. With at most 15 cities, a bitmask dynamic program (Held–Karp) over visited sets is fast enough.

Implement shortest_tour(distances).

Input

distances: An n × n matrix of travel costs; distances[i][i] = 0.

Output

Return the cost of the cheapest round trip.

Constraints

1 ≤ n ≤ 15; 0 ≤ cost ≤ 1,000,000

Examples

Example 1
Input:
distances = [
    [0, 10, 15, 20],
    [10, 0, 35, 25],
    [15, 35, 0, 30],
    [20, 25, 30, 0]
]

Expected output:
expected = 80
Input:
std::vector<std::vector<long long>> distances = {
    {0, 10, 15, 20},
    {10, 0, 35, 25},
    {15, 35, 0, 30},
    {20, 25, 30, 0}
};

Expected output:
long long expected = 80;
Input:
long[][] distances = new long[][] {
    new long[] {0, 10, 15, 20},
    new long[] {10, 0, 35, 25},
    new long[] {15, 35, 0, 30},
    new long[] {20, 25, 30, 0}
};

Expected output:
long expected = 80;

Explanation

0→1→3→2→0 costs 10 + 25 + 30 + 15 = 80, the cheapest tour.

Example 2
Input:
distances = [
    [0]
]

Expected output:
expected = 0
Input:
std::vector<std::vector<long long>> distances = {
    {0}
};

Expected output:
long long expected = 0;
Input:
long[][] distances = new long[][] {
    new long[] {0}
};

Expected output:
long expected = 0;

Explanation

With one city there is nowhere to go: 0.

How to approach it

Try on your own first, then open one hint at a time.

Hint 1

Since the city count is small, try tracking which cities have been visited instead of enumerating all tours directly.

Hint 2

Use dynamic programming over subsets of cities and remember the best cost to end at each city with that visited set.

Hint 3

Be careful to start and end at city 0, and to handle the cases where some paths are extremely expensive but still valid.

Expected complexity

O(n^2 2^n) time, O(n 2^n) extra space

References

This challenge is adapted for CodeUtility. Follow the statement and constraints above.

Learn from others

Community solutions

No published solutions yet. Solve this challenge to share the first one.