Problem · Matrix
Shortest Path in a Grid with Obstacles Elimination
Learn this problemProblem statement
You are given an m x n binary grid. A value of 0 is an empty cell and a value of 1 is an obstacle. Starting at the top-left cell, you may move one step up, down, left, or right.
You may eliminate at most k obstacles. Return the minimum number of steps needed to reach the bottom-right cell, or -1 when it is impossible.
Function
shortestPath(grid: int[][], k: int) → intExamples
Example 1
grid = [[0,0,0],[1,1,0],[0,0,0],[0,1,1],[0,0,0]]k = 1return = 6Eliminating one obstacle allows a shortest route of six steps.
Example 2
grid = [[0,1,1],[1,1,1],[1,0,0]]k = 1return = -1Every route to the destination requires eliminating more than one obstacle.
Constraints
1 <= m, n <= 401 <= m * ngrid[i][j]is either0or1.grid[0][0] == 0andgrid[m - 1][n - 1] == 0.0 <= k <= m * n