Shortest Path in a Grid with Obstacles Elimination
Problem Statement
You are given an m × n grid. A 0 is an empty cell and a 1 is an obstacle. You start at the top-left cell and want to reach the bottom-right cell.
Each move goes up, down, left or right into a neighbouring cell. You may remove up to k obstacles on the way: stepping onto an obstacle and removing it is allowed while you still have removals left. The start and end cells are empty.
Return the fewest moves needed to reach the bottom-right cell. Return -1 if no walk does it with at most k removals.
grid, an m × n grid of 0 and 1, and k, the number of obstacles you may remove.
The fewest moves from the top-left to the bottom-right cell, or -1.
Going round the obstacles without removing any takes 10 moves. Removing the obstacle at (3,2) gives a 6-move walk: (0,0) → (0,1) → (0,2) → (1,2) → (2,2) → (3,2) → (4,2).
Reaching the end needs at least two removals, but only one is allowed.
- • 1 ≤ m, n ≤ 40
- • 1 ≤ k ≤ m · n
- • Each cell is 0 or 1.
- • grid[0][0] = grid[m − 1][n − 1] = 0
Pattern Recognition Clues
Recognising these key signals in the problem description immediately identifies the pattern:
Approach Complexity Ladder
DFS over simple paths; each path carries how many obstacles it may still remove
BFS over states (cell, removals left); skip a state that a better one already covers
Walk every simple path from the top-left cell, carrying the number of removals left. Stepping onto an obstacle uses one removal, and a path with none left is cut. Keep the fewest moves that reach the end. Every path is walked on its own, so the work is exponential.
Recognition rule for this sub-pattern:
Unlock Complete Visual Walkthrough & Optimal C++
The interactive animated dry-run player, optimized C++ implementation, state invariant derivations, and edge-case breakdown for this question are part of Brute2Best Pro. The anchor question of every sub-pattern is completely free.
First anchor question per pattern, Part 1 LLD & Module 1 C++ basics are 100% Free forever.
How this concept connects to System Design & C++ Systems
Top engineering interviews test whether you understand how algorithms like Graph BFS / DFS translate into production architectures and low-level memory mechanics.