Full answer
Problem
Given an R x C grid of 0 (empty) and 1 (wall) and an integer k, return the minimum number of 4-directional steps from (0, 0) to (R-1, C-1) when up to k walls may be removed along the way, or -1 if impossible. Start and end are empty.
Example: for
0 0 0
1 1 0
0 0 0
0 1 1
0 0 0
with k = 1, the answer is 6 (break the wall at (3, 2)). For [[0,1,1],[1,1,1],[1,0,0]] with k = 1 the answer is -1.
Constraints: 1 <= R, C <= 40, 1 <= k <= R * C.
Brute force
Try every set of at most k walls to remove and run BFS on each modified grid: O(C(W, k) * R * C) for W walls, exponential in k.
Optimal approach
BFS where a state is (r, c, left):
- Shortcut: if
k >= R + C - 2, returnR + C - 2. - Start with
(0, 0, k)at 0 steps. - From a state, move to each neighbour; entering a wall reduces
leftby 1. Skip ifleftwould be negative. - Keep
best_left[r][c], the most removals left with which the cell was reached. Only enqueue a new state when it beats that value. - Return the step count when the target is popped.
Why it works
The extra coordinate makes the problem a plain unweighted shortest path over states, so BFS returns the minimum steps. The pruning is safe because BFS processes states in non-decreasing step order: a later visit to the same cell has at least as many steps, so it is only useful if it has strictly more removals left. The Manhattan shortcut holds because a monotone path has R + C - 2 steps and at most R + C - 3 interior cells.
Complexity
O(R * C * k) states, each with 4 moves: O(R * C * k) time and space in the worst case. The shortcut caps k at R + C - 3 effective values, so the bound is also O(R * C * (R + C)).
Code
import random
from collections import deque
from itertools import combinations
def shortest_with_k_removals(grid, k):
"""Fewest 4-directional steps from top-left to bottom-right when up to k walls (1s)
may be removed. BFS over states (row, col, removals_left). O(R * C * k)."""
n, m = len(grid), len(grid[0])
if k >= n + m - 2:
return n + m - 2 # enough removals to walk the Manhattan path
best_left = [[-1] * m for _ in range(n)] # most removals left seen at each cell
best_left[0][0] = k
q = deque([(0, 0, k, 0)])
while q:
r, c, left, steps = q.popleft()
if (r, c) == (n - 1, m - 1):
return steps
for nr, nc in ((r + 1, c), (r - 1, c), (r, c + 1), (r, c - 1)):
if 0 <= nr < n and 0 <= nc < m:
nl = left - grid[nr][nc]
if nl > best_left[nr][nc]: # dominates every earlier visit with fewer removals left
best_left[nr][nc] = nl
q.append((nr, nc, nl, steps + 1))
return -1
def brute(grid, k):
"""Try every set of at most k removed walls, run plain BFS on each."""
n, m = len(grid), len(grid[0])
walls = [(r, c) for r in range(n) for c in range(m) if grid[r][c]]
best = -1
for t in range(min(k, len(walls)) + 1):
for removed in combinations(walls, t):
rem = set(removed)
if grid[0][0] and (0, 0) not in rem:
continue
dist = {(0, 0): 0}
q = deque([(0, 0)])
while q:
r, c = q.popleft()
for nr, nc in ((r + 1, c), (r - 1, c), (r, c + 1), (r, c - 1)):
if 0 <= nr < n and 0 <= nc < m and (nr, nc) not in dist and (grid[nr][nc] == 0 or (nr, nc) in rem):
dist[(nr, nc)] = dist[(r, c)] + 1
q.append((nr, nc))
d = dist.get((n - 1, m - 1))
if d is not None and (best == -1 or d < best):
best = d
return best
if __name__ == "__main__":
g = [[0, 0, 0], [1, 1, 0], [0, 0, 0], [0, 1, 1], [0, 0, 0]]
assert shortest_with_k_removals(g, 1) == 6
assert shortest_with_k_removals([[0, 1, 1], [1, 1, 1], [1, 0, 0]], 1) == -1
assert shortest_with_k_removals([[0]], 0) == 0
rng = random.Random(77)
for _ in range(300):
n, m = rng.randint(1, 4), rng.randint(1, 4)
grid = [[int(rng.random() < 0.4) for _ in range(m)] for _ in range(n)]
grid[0][0] = grid[-1][-1] = 0
k = rng.randint(0, 2)
assert shortest_with_k_removals(grid, k) == brute(grid, k)
print("all tests passed")Save as b77_grid_obstacle_elimination.py and run python3 b77_grid_obstacle_elimination.py. It prints all tests passed (Python 3.13.5).
Edge cases
k = 0 (plain BFS). Single-cell grid (0 steps). k large enough for the shortcut. Walls everywhere except the corners. A visited set on (r, c) alone is wrong because it discards a state with more removals left.
Pattern
BFS on an expanded state space: add whatever resource or flag changes future options to the node identity. Same idea: keys and doors (bitmask of keys), shortest path visiting all nodes (bitmask of visited), fuel-limited routes, and the k-stops flight problem.
import random
from collections import deque
from itertools import combinations
def shortest_with_k_removals(grid, k):
"""Fewest 4-directional steps from top-left to bottom-right when up to k walls (1s)
may be removed. BFS over states (row, col, removals_left). O(R * C * k)."""
n, m = len(grid), len(grid[0])
if k >= n + m - 2:
return n + m - 2 # enough removals to walk the Manhattan path
best_left = [[-1] * m for _ in range(n)] # most removals left seen at each cell
best_left[0][0] = k
q = deque([(0, 0, k, 0)])
while q:
r, c, left, steps = q.popleft()
if (r, c) == (n - 1, m - 1):
return steps
for nr, nc in ((r + 1, c), (r - 1, c), (r, c + 1), (r, c - 1)):
if 0 <= nr < n and 0 <= nc < m:
nl = left - grid[nr][nc]
if nl > best_left[nr][nc]: # dominates every earlier visit with fewer removals left
best_left[nr][nc] = nl
q.append((nr, nc, nl, steps + 1))
return -1
def brute(grid, k):
"""Try every set of at most k removed walls, run plain BFS on each."""
n, m = len(grid), len(grid[0])
walls = [(r, c) for r in range(n) for c in range(m) if grid[r][c]]
best = -1
for t in range(min(k, len(walls)) + 1):
for removed in combinations(walls, t):
rem = set(removed)
if grid[0][0] and (0, 0) not in rem:
continue
dist = {(0, 0): 0}
q = deque([(0, 0)])
while q:
r, c = q.popleft()
for nr, nc in ((r + 1, c), (r - 1, c), (r, c + 1), (r, c - 1)):
if 0 <= nr < n and 0 <= nc < m and (nr, nc) not in dist and (grid[nr][nc] == 0 or (nr, nc) in rem):
dist[(nr, nc)] = dist[(r, c)] + 1
q.append((nr, nc))
d = dist.get((n - 1, m - 1))
if d is not None and (best == -1 or d < best):
best = d
return best
if __name__ == "__main__":
g = [[0, 0, 0], [1, 1, 0], [0, 0, 0], [0, 1, 1], [0, 0, 0]]
assert shortest_with_k_removals(g, 1) == 6
assert shortest_with_k_removals([[0, 1, 1], [1, 1, 1], [1, 0, 0]], 1) == -1
assert shortest_with_k_removals([[0]], 0) == 0
rng = random.Random(77)
for _ in range(300):
n, m = rng.randint(1, 4), rng.randint(1, 4)
grid = [[int(rng.random() < 0.4) for _ in range(m)] for _ in range(n)]
grid[0][0] = grid[-1][-1] = 0
k = rng.randint(0, 2)
assert shortest_with_k_removals(grid, k) == brute(grid, k)
print("all tests passed")State-space BFS with best-removals-left pruning and the Manhattan shortcut; random grids are checked by trying every subset of removed walls.
Complexity
Time: O(R * C * k). Space: O(R * C * k) worst case. With pruning, typical runs explore far fewer states; the shortcut bounds effective k by R + C - 3.
By level
Fresher: Explains why tracking only cells fails, using a small grid where a path with more removals left matters. Writes BFS over (row, col, left).
Mid: Adds the best-left pruning and the Manhattan shortcut and argues why both are safe. States the state-space complexity.
Senior: Generalizes state expansion to keys, fuel and visited-set bitmasks and estimates state counts before choosing the method. Discusses A* with Manhattan distance and memory limits on larger grids.
Key points
- State = (row, col, removals left)
- BFS over states gives minimum steps
- Prune states with fewer removals left than seen
- Manhattan shortcut when k is large
- Visited on cells alone is wrong
Common mistakes
- Using a visited set keyed only by cell
- Decrementing k when entering empty cells
- Missing the large-k shortcut and timing out
- Using DFS for a shortest path
Follow-ups
- How would you solve a maze with keys and doors?
- What if removing a wall costs differently per wall?
- How would A* help here?
Tips
- Explain why the state must include k
- Justify the pruning with BFS order
- Mention the shortcut early
Evaluation rubric
- Correct state definition
- Correct pruning argument
- Correct complexity
- Handles edge cases