Problem · Matrix
Minimum-Cost Path Through a Weighted Grid
Learn this problemProblem statement
You are given a rectangular integer grid. A value of -1 marks a blocked cell; every other value is the nonnegative cost of entering that cell.
Start at the top-left cell and reach the bottom-right cell using only up, down, left, or right moves. Return the minimum total cost, including the costs of both the start and destination cells. Return -1 if either endpoint is blocked or no valid path exists.
Function
minimumWeightedGridPathCost(grid: int[][]) → longExamples
Example 1
grid = [[1,3,1],[1,5,1],[4,2,1]]return = 7One minimum route has costs 1, 3, 1, 1, and 1 for a total of 7.
Example 2
grid = [[1,-1],[-1,2]]return = -1The destination is open, but both possible first moves are blocked.
Example 3
grid = [[9]]return = 9The single cell is both endpoints, so its weight is the complete path cost.
Constraints
1 <= rows, columns <= 500.- The grid is rectangular and contains at most
200000cells. - Each value is
-1or lies in[0, 1000000]. - Every reachable path cost fits a signed 64-bit integer.