Shortest Path in a Grid with Obstacles Elimination

You are given an `m x n` integer matrix `grid` where each cell is `0` (empty) or `1` (obstacle). In one step you can move up, down, left or right to an empty cell. Return the minimum number of steps to walk from the upper left corner `(0, 0)` to the lower right corner `(m - 1, n - 1)` given that you can eliminate at most `k` obstacles. If no such walk exists, return `-1`.

30:00

Shortest Path in a Grid with Obstacles Elimination
hard
Free written solution
Topics
Companies

You are given an m x n integer matrix grid where each cell is 0 (empty) or 1 (obstacle). In one step you can move up, down, left or right to an empty cell. Return the minimum number of steps to walk from the upper left corner (0, 0) to the lower right corner (m - 1, n - 1) given that you can eliminate at most k obstacles. If no such walk exists, return -1.

Example 1:
Input: {"grid":[[0,0,0],[1,1,0],[0,0,0],[0,1,1],[0,0,0]],"k":1}
Output: 6
Constraints:
  • m==grid.lengthm == \text{grid.length}

  • n==grid[i].lengthn == \text{grid}[i].\text{length}

  • 1≤m,n≤401 \leq m, n \leq 40

  • 1≤k≤m⋅n1 \leq k \leq m \cdot n

  • grid[i][j]\text{grid}[i][j] is either 00 or 11

  • grid[0][0]==grid[m−1][n−1]==0\text{grid}[0][0] == \text{grid}[m - 1][n - 1] == 0

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"grid":[[0,0,0],[1,1,0],[0,0,0],[0,1,1],[0,0,0]],"k":1}

Start at (0,0) with k = 1 eliminations. best[r][c] will hold the most eliminations anyone had left on reaching that cell.

moves

0

k left here

1/1

queue

1

answer

...

S####T

obstacle

obstacle walked through

reached, number = most k left

shortest route

Variables
VariableValue
k1
best[0][0]1
queue1
DepthFunction Call
Stack empty
0/24