Shortest Round Trip Through All Deliveries
Problem statement
You are given a rectangular grid containing one start, open cells, obstacles, and delivery points:
Sis the unique start.Dis a delivery point..is an open cell.#is an obstacle.
From an open cell, the courier may move one cell up, down, left, or right at unit cost. The courier must start at S, visit every D at least once in any order, and return to S.
Return the minimum total travel distance. Return -1 when no such round trip exists. Only the distance is required, so equally short routes need no tie-breaker.
Function
shortestDeliveryRoundTrip(grid: String[]) → intExamples
Example 1
grid = ["S.D","...","D.."]return = 8Each delivery is two steps from the start, and the two deliveries are four steps apart. Visiting them in either order and returning costs 2 + 4 + 2 = 8.
Example 2
grid = ["S..#","##.#","D..D"]return = 14The start-to-left-delivery distance is 6, the delivery-to-delivery distance is 3, and the right delivery is 5 steps from the start. The minimum round trip therefore costs 14.
Constraints
1 <= grid.length <= 30.1 <= grid[i].length <= 30, and every row has the same length.- Each cell is
S,D,., or#. - The grid contains exactly one
Sand from1through9cells markedD.