Minimum Distance to Return a Book
Problem statement
You are given a rectangular map grid, a starting coordinate start, and the direct train distance from every train station to its closest library.
Each cell in grid is one of:
., an open cell;#, a blocked cell;L, a library; orT, a train station.
You may walk one cell up, down, left, or right at a cost of 1, staying inside the map and never entering a blocked cell. Libraries and train stations are walkable.
The values in stationToLibrary correspond to the T cells in row-major order. Reaching a train station lets you immediately finish the trip at that station's closest library for the corresponding additional train distance.
Return the minimum total distance needed to return the book. A valid trip either walks directly onto a library or walks to a train station and then uses its direct connection. Return -1 when neither option is reachable.
Function
minimumLibraryReturnDistance(grid: String[], start: int[], stationToLibrary: int[]) → intExamples
Example 1
grid = ["...L",".##.","T..."]start = [0,0]stationToLibrary = [2]return = 3Walking right three times reaches the library at [0,3]. Walking two steps to the station and then traveling distance 2 would cost 4.
Example 2
grid = ["L###","###T","...."]start = [2,0]stationToLibrary = [2]return = 6The library cannot be reached by walking. The station at [1,3] is four walking steps away, and its direct train distance is 2.
Example 3
grid = ["L#T","###","..."]start = [2,1]stationToLibrary = [3]return = -1The blocked middle row separates the start from both the library and the train station.
Constraints
1 <= grid.lengthand1 <= grid[row].length.- All rows have the same length, and the map contains at most
200000cells. - Every cell is one of
.,#,L, orT. - The map contains at least one library.
startis an in-bounds coordinate whose cell is not blocked.stationToLibrary.lengthequals the number of train stations.0 <= stationToLibrary[i] <= 10^9.