Shortest Path in a Grid with Obstacles Elimination
Hard
Topics
grid holds 0 for an empty cell and 1 for an obstacle. You start at the top-left cell and want the bottom-right cell, moving up, down, left or right one step at a time.
You may remove at most k obstacles along the way. Return the fewest steps needed, or -1 if the finish cannot be reached.
Example 1
Input: grid = [[0,0,0],[1,1,0],[0,0,0]], k = 1 Output: 4 Explanation: Going down the right-hand column needs no removals and takes 4 steps.
Example 2
Input: grid = [[0,1,1],[1,1,1],[1,0,0]], k = 1 Output: -1 Explanation: Any route needs at least two removals, and only one is allowed.
Example 3
Input: grid = [[0,0],[1,0]], k = 0 Output: 2 Explanation: With no removals permitted the route still exists, across the top and down.
Constraints
- 1 <= grid.length, grid[0].length <= 40
- grid[i][j] is 0 or 1
- 1 <= k <= grid.length * grid[0].length
- grid[0][0] == grid[m-1][n-1] == 0
Editorial — intuition, approach, complexity and pitfalls
Intuition
Without obstacle removal this is a plain ring-by-ring walk over cells. Removal breaks that, and the reason is worth being precise about: a cell is no longer either visited or not. Arriving at a cell having spent 2 removals is a different situation from arriving having spent 0, because the second leaves more options ahead.
So the thing being explored is not a cell, it is a pair: which cell, and how many removals used so far. Mark those pairs as visited rather than cells, and the ordinary ring-by-ring walk is correct again, because every step still costs exactly one.
This is the single mistake that sinks most attempts. Marking cells alone means the first arrival wins and later arrivals with a healthier removal budget are discarded, so a route that was briefly more expensive but cheaper overall is never found.
One refinement is worth knowing: arriving at a cell with more removals left than some earlier arrival is strictly better, so a budget worse than one already recorded for that cell can be dropped. Tracking the best remaining budget per cell is a smaller visited set than the full pair set and prunes the same branches.
Approach
- The state is
(row, col, used)whereusedis the number of obstacles removed so far. - Explore outward from
(0, 0, 0)at distance 0, ring by ring, so the first arrival at the finish is the fewest steps. - For each of the four neighbours, compute the new
used: unchanged for an empty cell, one more for an obstacle. - Discard the move when
usedwould exceedk. - Mark
(row, col, used)visited rather than(row, col), or keep the best remaining budget per cell and discard any arrival that is no better. - Return the distance when the finish is reached, and
-1if the exploration empties.
Walkthrough
grid = [[0,0,0],
[1,1,0],
[0,0,0]]
k = 1
the route that needs no removal
(0,0) -> (0,1) -> (0,2) -> (1,2) -> (2,2)
4 steps, used 0
there is also a route THROUGH an obstacle
(0,0) -> (1,0) removes the obstacle, used 1
-> (2,0) -> (2,1) -> (2,2)
also 4 steps, used 1
both are 4, so the answer is 4
why the state must include `used`
consider arriving at (1,2) two ways:
from (0,2), used 0
from (2,2), used 0
same budget, so one can be discarded. But if a route
arrived at (1,2) having used 1, and a cheaper-in-steps
route arrived having used 0, discarding the second
because the cell was "already visited" throws away the
only route that can still afford an obstacle later.
grid = [[0,1,1],[1,1,1],[1,0,0]], k = 1
every route from (0,0) to (2,2) crosses at least two
obstacles, and only one removal is allowed
answer -1Complexity
- Time — O(rows * cols * k): each cell is reachable with each of the k + 1 budgets, and each such state is expanded once.
- Space — O(rows * cols * k): the visited set over states.
Common Pitfalls
- Marking cells visited instead of cell-and-budget pairs. This is the central mistake and it silently returns a value that is too large, or
-1. - Forgetting the single-cell grid, where the start is already the finish and the answer is 0.
- Adding the obstacle cost of the cell you are leaving rather than the one you are entering.
- Using a cost-ordered queue. Every step costs 1, so a plain ring-by-ring walk is already correct and simpler.
- Allowing
usedto reachk + 1before checking, which permits one removal too many.
Full Solution — all languages
class Solution:
def shortestPath(self, grid, k):
from collections import deque
rows, cols = len(grid), len(grid[0])
if rows == 1 and cols == 1:
return 0
# The state is (cell, removals used) -- NOT just the cell. Arriving
# with a different budget is a genuinely different situation.
seen = {(0, 0, 0)}
queue = deque([(0, 0, 0, 0)]) # row, col, used, steps
while queue:
r, c, used, steps = queue.popleft()
for dr, dc in ((1, 0), (-1, 0), (0, 1), (0, -1)):
nr, nc = r + dr, c + dc
if not (0 <= nr < rows and 0 <= nc < cols):
continue
spent = used + grid[nr][nc]
if spent > k:
continue
if nr == rows - 1 and nc == cols - 1:
return steps + 1
if (nr, nc, spent) not in seen:
seen.add((nr, nc, spent))
queue.append((nr, nc, spent, steps + 1))
return -1import java.util.*;
class Solution {
public int shortestPath(int[][] grid, int k) {
int rows = grid.length, cols = grid[0].length;
if (rows == 1 && cols == 1) return 0;
// seen[r][c] = smallest number of removals used on arrival here.
int[][] seen = new int[rows][cols];
for (int[] row : seen) Arrays.fill(row, Integer.MAX_VALUE);
seen[0][0] = 0;
Deque<int[]> queue = new ArrayDeque<>();
queue.add(new int[]{0, 0, 0, 0});
int[][] dirs = { {
1, 0
},
{
-1, 0
},
{
0, 1
},
{
0, -1
}
};
while (!queue.isEmpty()) {
int[] cur = queue.poll();
for (int[] d : dirs) {
int nr = cur[0] + d[0], nc = cur[1] + d[1];
if (nr < 0 || nc < 0 || nr >= rows || nc >= cols) continue;
int spent = cur[2] + grid[nr][nc];
if (spent > k) continue;
if (nr == rows - 1 && nc == cols - 1) return cur[3] + 1;
if (spent < seen[nr][nc]) {
seen[nr][nc] = spent;
queue.add(new int[]{nr, nc, spent, cur[3] + 1});
}
}
}
return -1;
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: int shortestPath(vector<vector<int>>& grid, int k) {
int rows = (int)grid.size(), cols = (int)grid[0].size();
if (rows == 1 && cols == 1) return 0;
// seen[r][c] = smallest number of removals used on arrival here.
vector<vector<int>> seen(rows, vector<int>(cols, INT_MAX));
seen[0][0] = 0;
queue<array<int, 4>> q;
q.push({0, 0, 0, 0});
int dirs[4][2] = { {
1, 0
},
{
-1, 0
},
{
0, 1
},
{
0, -1
}
};
while (!q.empty()) {
auto cur = q.front();
q.pop();
for (int d = 0; d < 4; d++) {
int nr = cur[0] + dirs[d][0], nc = cur[1] + dirs[d][1];
if (nr < 0 || nc < 0 || nr >= rows || nc >= cols) continue;
int spent = cur[2] + grid[nr][nc];
if (spent > k) continue;
if (nr == rows - 1 && nc == cols - 1) return cur[3] + 1;
if (spent < seen[nr][nc]) {
seen[nr][nc] = spent;
q.push({nr, nc, spent, cur[3] + 1});
}
}
}
return -1;
}
};/**
* @param {number[][]} grid
* @param {number} k
* @return {number}
*/ var shortestPath = function(grid, k) {
const rows = grid.length, cols = grid[0].length;
if (rows === 1 && cols === 1) return 0;
const seen = new Set(["0,0,0"]);
const queue = [[0, 0, 0, 0]];
let head = 0;
const dirs = [[1, 0], [-1, 0], [0, 1], [0, -1]];
while (head < queue.length) {
const [r, c, used, steps] = queue[head++];
for (const [dr, dc] of dirs) {
const nr = r + dr, nc = c + dc;
if (nr < 0 || nc < 0 || nr >= rows || nc >= cols) continue;
const spent = used + grid[nr][nc];
if (spent > k) continue;
if (nr === rows - 1 && nc === cols - 1) return steps + 1;
const key = nr + "," + nc + "," + spent;
if (!seen.has(key)) {
seen.add(key);
queue.push([nr, nc, spent, steps + 1]);
}
}
}
return -1;
};