Problem description:

You are given an m x n integer matrix grid where each cell is either 0 (empty) or 1 (obstacle). You can move up, down, left, or right from and to an empty cell in one step.

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 it is not possible to find such walk return -1.

Example 1:

1
2
3
4
5
6
7
8
9
10
11
12
Input:
grid =
[[0,0,0],
 [1,1,0],
[0,0,0],
 [0,1,1],
[0,0,0]],
k = 1
Output: 6
Explanation:
The shortest path without eliminating any obstacle is 10.
The shortest path with one obstacle elimination at position (3,2) is 6. Such path is(0,0) -> (0,1) -> (0,2) -> (1,2) -> (2,2) ->(3,2) -> (4,2).

Example 2:

1
2
3
4
5
6
7
8
9
Input:
grid =
[[0,1,1],
 [1,1,1],
 [1,0,0]],
k = 1
Output: -1
Explanation:
We need to eliminate at least two obstacles to find such a walk.

Constraints:

  • m == grid.length
  • n == grid[i].length
  • 1 <= m, n <= 40
  • 1 <= k <= m * n
  • grid[i][j] == 0 **or** 1
  • grid[0][0] == grid[m - 1][n - 1] == 0

Solution:

Straight-forward BFS.

Duplicate computation happens when we reach to (i,j) with same left change k , use a set to save time

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution:
def shortestPath(self, grid: List[List[int]], k: int) -> int:
m, n = len(grid), len(grid[0])
if m == 1 and n == 1:
return 0

q = deque([(0, 0, 0, k)]) # i, j, moves, k
visited = set((0,0,k))
while q:
i, j, move, k = q.popleft()
for nx, ny in [(i+1,j), (i-1,j), (i,j+1),(i,j-1)]:
if nx == m-1 and ny == n-1:
return move+1

if 0 <= nx < m and 0 <= ny < n:
if grid[nx][ny] == 1 and k > 0 and (nx, ny, k-1) not in visited:
visited.add((nx,ny,k-1))
q.append((nx, ny, move+1, k-1))
if grid[nx][ny] == 0 and (nx, ny, k) not in visited:
visited.add((nx,ny,k))
q.append((nx, ny, move+1, k))
return -1

time: O(mnk), for every cell (m*n), in the worst case we have to put that cell into the queue/bfs k times.

space: O(mnk), in the worst case we have to put that cell into the queue/bfs k times which means we need to worst case store all of those steps/paths in the visited set.

time complexity: $O()$
space complexity: $O()$
reference:
related problem: