Algo-Sim › Grid Graphs
Shortest Path in a Grid with Obstacles Elimination
Hard · Grid Graphs · step through it in Java, Python and C++ on your own input
BFS over states (row, col, eliminations left): the same cell reached with more eliminations to spare is a different, better state.
Problem
A grid has empty cells (0) and obstacles (1). You move up, down, left or right, and may remove at most k obstacles on the way. Return the fewest steps from the top-left to the bottom-right, or -1 if it cannot be done. Both corners are empty.
Constraints
- 1 ≤ m, n ≤ 40
- 1 ≤ k ≤ m·n
- grid[0][0] = grid[m − 1][n − 1] = 0
Edge cases to test
- k ≥ m + n − 3: the Manhattan distance is the answer
- The start is the goal:
0 - No path even with k removals
Follow-up questions
- Why add k to the state?
- Reaching a cell with more removals left can lead to paths the earlier visit could not, so (r, c, k) are different states: O(m·n·k).
- Is there a shortcut?
- A Manhattan path crosses m + n − 3 cells between the corners, so if k ≥ m + n − 3, return m + n − 2 at once.
Solution
Java
public int shortestPath(int[][] grid, int k) {
int rows = grid.length, cols = grid[0].length;
boolean[][][] seen = new boolean[rows][cols][k + 1];
// A state is { row, col, eliminations left }: the same cell with more left is a different state.
Queue<int[]> queue = new ArrayDeque<>();
queue.offer(new int[] { 0, 0, k });
seen[0][0][k] = true;
int[][] dirs = { { 1, 0 }, { -1, 0 }, { 0, 1 }, { 0, -1 } };
for (int steps = 0; !queue.isEmpty(); steps++) {
for (int size = queue.size(); size > 0; size--) {
int[] cur = queue.poll();
if (cur[0] == rows - 1 && cur[1] == cols - 1) return steps;
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 left = cur[2] - grid[nr][nc]; // an obstacle costs one
if (left < 0 || seen[nr][nc][left]) continue;
seen[nr][nc][left] = true;
queue.offer(new int[] { nr, nc, left });
}
}
}
return -1;
}Python
from collections import deque
def shortest_path(grid, k):
rows, cols = len(grid), len(grid[0])
# A state is (row, col, eliminations left).
queue = deque([(0, 0, k)])
seen = {(0, 0, k)}
steps = 0
while queue:
for _ in range(len(queue)):
r, c, left = queue.popleft()
if r == rows - 1 and c == cols - 1:
return steps
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
nleft = left - grid[nr][nc] # an obstacle costs one
if nleft < 0 or (nr, nc, nleft) in seen:
continue
seen.add((nr, nc, nleft))
queue.append((nr, nc, nleft))
steps += 1
return -1C++
#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());
vector<vector<vector<bool>>> seen(rows, vector<vector<bool>>(cols, vector<bool>(k + 1)));
// A state is { row, col, eliminations left }.
deque<array<int, 3>> queue;
queue.push_back({0, 0, k});
seen[0][0][k] = true;
vector<vector<int>> dirs = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
for (int steps = 0; !queue.empty(); steps++) {
for (int size = int(queue.size()); size > 0; size--) {
auto [r, c, left] = queue.front();
queue.pop_front();
if (r == rows - 1 && c == cols - 1)
return steps;
for (vector<int> &d : dirs) {
int nr = r + d[0], nc = c + d[1];
if (nr < 0 || nc < 0 || nr >= rows || nc >= cols)
continue;
int next = left - grid[nr][nc];
if (next < 0 || seen[nr][nc][next])
continue;
seen[nr][nc][next] = true;
queue.push_back({nr, nc, next});
}
}
}
return -1;
}
};
More Grid Graphs problems
- Flood Fill (Easy)
- Number of Islands (BFS) (Medium)
- Number of Islands (DFS) (Medium)
- Max Area of Island (Medium)
- Rotting Oranges (Medium)
- 01 Matrix (Medium)
- Walls and Gates (Medium)
- Shortest Path in Binary Matrix (Medium)
- Shortest Bridge (Medium)
- Surrounded Regions (Medium)
- Pacific Atlantic Water Flow (Medium)
- Path With Minimum Effort (Medium)
- Minimum Cost to Make at Least One Valid Path in a Grid (Hard)
- Swim in Rising Water (Hard)