Minimum-Weight Path Through a Matrix
Problem statement
Given a square matrix grid, find the minimum travel cost from its top-left cell to its bottom-right cell. A cell with value -1 is blocked. Every other value is the nonnegative cost of entering that cell.
You may move to any of the eight neighboring cells, including diagonals. The starting cell is not charged; every later entered cell contributes its value. Return the minimum total cost, or -1 if the destination cannot be reached.
Function
minimumWeightedPathCost(grid: int[][]) → intExamples
Example 1
grid = [[0,5],[2,1]]return = 1The diagonal enters the destination at cost 1; the starting cell is free.
Example 2
grid = [[0,9,9],[1,-1,1],[2,1,0]]return = 2Move through the cost-1 cell at (1,0), then the cost-1 cell at (2,1), then the cost-0 destination.
Example 3
grid = [[0,-1,2],[-1,-1,1],[2,1,0]]return = -1All three neighboring cells of the start are blocked, so no path reaches the destination.
Constraints
1 <= grid.length <= 50and every row has exactlygrid.lengthcells.- Each cell is
-1or an integer from0through1000. - Costs are nonnegative, so revisiting a cell cannot improve a minimum-cost path.