Parcel-delivery app~40 min2s · 256 MBtarget O(n^3 + 2^n × n^2) time, O(2^n × n) spaceclassic twin: lc-847dp
A freight company serves one region with n depots. A van must call at every depot once or more, to collect the day's pallets. It can start at any depot and does not drive home afterwards.
Roads connect pairs of depots, and each road has a length in kilometres. The van may pass through a depot it has already served, if that gives a shorter drive. Dispatch wants the shortest total distance.
Write shortest_tour(n, roads).
0 to n - 1.roads[i] = [a, b, w] is a two-way road between depots a and b of length w. Two depots may have more than one road between them.n depots.Input: n = 4, roads = [[0, 1, 5], [1, 2, 2], [1, 3, 4], [0, 3, 9]]
Output: 13First work out the shortest distance between every two depots, passing through others where that helps. Depots 0 and 2 are 7 apart, through depot 1, and depots 2 and 3 are 6 apart.
| Step | What happens | Cheapest cost |
|---|---|---|
| [3] | Depots 1 and 2 visited, ending at either | 2 |
| [4] | Depots 0, 1 and 2 visited, ending at 0, 1 or 2 | 7, 9, 7 |
| [4] | All four depots visited, ending at 0, 1, 2 or 3 | 13, 17, 15, 13 |
| [5] | Take the cheapest ending | 13 |
One drive of 13 is 0 → 1 → 2 → 1 → 3: 5 + 2 + 2 + 4. It passes through depot 1 twice.
Input: n = 3, roads = [[0, 1, 10], [1, 2, 1], [0, 2, 3]]
Output: 4Start at depot 1, drive to depot 2 (1), then to depot 0 (3). The direct road from 0 to 1 is 10, so it is never used.
Input: n = 1, roads = []
Output: 0One depot needs no driving.
1 ≤ n ≤ 140 ≤ len(roads) ≤ 120roads[i] has three entries: two depots from 0 to n - 1, and a length from 1 to 1000There are 14! = 87,178,291,200 orders in which the van can first reach the depots, so trying every order is impossible.
The set of depots served so far has only 2^14 = 16,384 possibilities, and the last depot has 14. That is 229,376 states, with at most 14 moves out of each, so a table over sets of depots is small.