Shortest Path in a Grid with Obstacles Elimination (LeetCode 1293): Solution and Explanation
Walk from the top left to the bottom right of a grid of empty cells and obstacles in as few steps as possible, where you may break through at most k obstacles along the way.
Intuition
Every move costs exactly one step, so the fewest steps is a breadth-first search question. The twist is that a cell is not simply visited or unvisited: reaching it with three eliminations left is more useful than reaching it with one, because the richer visit can still break walls later.
So the real state is (row, col, eliminations left). Stepping onto an obstacle moves you to the same kind of state with one fewer elimination. BFS over these states still visits them in order of steps taken, so the first time the bottom right corner comes off the queue, its level is the answer.
There is a cheap pruning rule. If some earlier visit reached a cell with at least as many eliminations left, a later visit is no better: it is at least as far from the start and has no more budget. Keeping best[r][c], the largest budget seen at each cell, and enqueueing only when the new budget beats it removes most of the duplicate states.
One more shortcut: any route needs at least m + n - 2 moves, and the staircase route (down the first column, then along the last row) uses exactly that many and crosses m + n - 3 cells in between. If k is at least m + n - 2, you can afford to break every one of them, so the answer is m + n - 2 straight away.
Approach: BFS over (row, col, eliminations left)
- If
k >= m + n - 2, returnm + n - 2. - Create
best[r][c] = -1for every cell, setbest[0][0] = k, and put(0, 0, k)in the queue. - Process the queue one level at a time, with
stepscounting the levels. - When the popped state is the bottom right corner, return
steps. - For each neighbour inside the grid, compute
nrem = rem - grid[nr][nc]. Ifnrem > best[nr][nc], store it and enqueue(nr, nc, nrem). A negativenremnever beatsbest, so walls you cannot afford are skipped automatically. - If the queue runs out, return
-1.
Step-by-step example
grid = [[0,0,0],[1,1,0],[0,0,0],[0,1,1],[0,0,0]], k = 1
- m + n - 2 = 6 and k = 1, so the shortcut does not apply. Start the queue with (0,0) holding 1 elimination.
- Level 0: from (0,0), moving right to (0,1) is free and keeps 1; moving down onto the wall at (1,0) spends it, leaving 0.
- The search spreads along the top row and also through the broken wall at (1,0) into (2,0) with 0 left.
- Cells reached with budget 1 keep expanding down the right column: (1,2), (2,2), then the wall at (3,2) costs the last elimination.
- (4,2) is reached from (3,2) with 0 left and comes off the queue at level 6, so the answer is 6. Without breaking any wall the walk would take 10 steps.
Code: Python, Java, C++
1class Solution:
2 def shortestPath(self, grid: List[List[int]], k: int) -> int:
3 m, n = len(grid), len(grid[0])
4 if k >= m + n - 2:
5 return m + n - 2
6 best = [[-1] * n for _ in range(m)]
7 best[0][0] = k
8 queue = deque([(0, 0, k)])
9 steps = 0
10 while queue:
11 for _ in range(len(queue)):
12 r, c, rem = queue.popleft()
13 if r == m - 1 and c == n - 1:
14 return steps
15 for dr, dc in ((1, 0), (-1, 0), (0, 1), (0, -1)):
16 nr, nc = r + dr, c + dc
17 if 0 <= nr < m and 0 <= nc < n:
18 nrem = rem - grid[nr][nc]
19 if nrem > best[nr][nc]:
20 best[nr][nc] = nrem
21 queue.append((nr, nc, nrem))
22 steps += 1
23 return -11class Solution {
2 public int shortestPath(int[][] grid, int k) {
3 int m = grid.length, n = grid[0].length;
4 if (k >= m + n - 2) return m + n - 2;
5 int[][] best = new int[m][n];
6 for (int[] row : best) Arrays.fill(row, -1);
7 best[0][0] = k;
8 Deque<int[]> queue = new ArrayDeque<>();
9 queue.offer(new int[]{0, 0, k});
10 int[][] dirs = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
11 int steps = 0;
12 while (!queue.isEmpty()) {
13 for (int size = queue.size(); size > 0; size--) {
14 int[] cur = queue.poll();
15 int r = cur[0], c = cur[1], rem = cur[2];
16 if (r == m - 1 && c == n - 1) return steps;
17 for (int[] d : dirs) {
18 int nr = r + d[0], nc = c + d[1];
19 if (nr < 0 || nr >= m || nc < 0 || nc >= n) continue;
20 int nrem = rem - grid[nr][nc];
21 if (nrem > best[nr][nc]) {
22 best[nr][nc] = nrem;
23 queue.offer(new int[]{nr, nc, nrem});
24 }
25 }
26 }
27 steps++;
28 }
29 return -1;
30 }
31}1class Solution {
2public:
3 int shortestPath(vector<vector<int>>& grid, int k) {
4 int m = grid.size(), n = grid[0].size();
5 if (k >= m + n - 2) return m + n - 2;
6 vector<vector<int>> best(m, vector<int>(n, -1));
7 best[0][0] = k;
8 queue<array<int, 3>> q;
9 q.push({0, 0, k});
10 int dirs[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
11 int steps = 0;
12 while (!q.empty()) {
13 for (int size = q.size(); size > 0; size--) {
14 auto [r, c, rem] = q.front();
15 q.pop();
16 if (r == m - 1 && c == n - 1) return steps;
17 for (auto& d : dirs) {
18 int nr = r + d[0], nc = c + d[1];
19 if (nr < 0 || nr >= m || nc < 0 || nc >= n) continue;
20 int nrem = rem - grid[nr][nc];
21 if (nrem > best[nr][nc]) {
22 best[nr][nc] = nrem;
23 q.push({nr, nc, nrem});
24 }
25 }
26 }
27 steps++;
28 }
29 return -1;
30 }
31};Time and space complexity
O(m * n * k)
Each cell can be enqueued at most once per distinct budget value, and each state checks four neighbours. With the m + n - 2 shortcut, k is effectively below m + n, so this is at most O(m * n * (m + n)).
O(m * n * k)
The queue can hold up to one entry per (cell, budget) pair in the worst case. The best array itself is only O(m * n).
Other approaches
BFS with a 3D visited array (time O(m * n * k), space O(m * n * k))
Mark visited[r][c][rem] instead of keeping the best budget per cell. Simpler to reason about but explores many dominated states that the best[] pruning skips.
A* search with Manhattan distance (time O(m * n * k * log(m * n * k)), space O(m * n * k))
Order states by steps so far plus the Manhattan distance to the corner. Often explores fewer states on open grids, at the cost of a priority queue.
0-1 BFS on walls broken (time O(m * n), space O(m * n))
Finds the fewest walls you must break, which answers whether a walk exists but not the fewest steps. Useful as a quick check, not as the full solution.
Common mistakes
- Using a plain 2D visited array. A cell first reached with 0 eliminations would block a later, richer visit that could still break a wall further on.
- Allowing the budget to go negative. Only step onto an obstacle when at least one elimination remains.
- Checking for the goal only when pushing, and forgetting the 1x1 grid, where the start is already the goal and the answer is 0.
- Skipping the k >= m + n - 2 shortcut on large k. It is not needed for correctness, but without it the state space can grow to m * n * k entries.
Frequently asked questions
Why is BFS still correct when the state includes the budget?
Every move costs one step whether or not it breaks a wall, so the graph of (row, col, budget) states is unweighted. BFS on an unweighted graph reaches each state at its smallest step count.
Why keep only the best budget per cell?
BFS pops states in order of steps. A later visit to the same cell has at least as many steps, so if it also has no more budget it can never lead to a shorter answer. Enqueueing only strictly better budgets is safe.
Why is m + n - 2 the shortcut threshold?
The staircase route has m + n - 2 moves and m + n - 3 middle cells. If k covers every middle cell, that route is always walkable, and nothing can be shorter than the Manhattan distance.
How is this different from Minimum Obstacle Removal?
That problem minimises walls broken with unlimited steps, a 0-1 BFS. Here walls are a limited budget and steps are what you minimise, so the budget becomes part of the state.