Minimum Obstacle Removal to Reach Corner - Problem

You are given a 0-indexed 2D integer array grid of size m x n. Each cell has one of two values:

  • 0 represents an empty cell
  • 1 represents an obstacle that may be removed

You can move up, down, left, or right from and to an empty cell.

Return the minimum number of obstacles to remove so you can move from the upper left corner (0, 0) to the lower right corner (m - 1, n - 1).

Input & Output

Example 1 — Basic Case
$ Input: grid = [[0,1,1],[1,1,0],[1,1,0]]
Output: 2
💡 Note: We can remove the obstacles at (0,1) and (0,2) to create path (0,0) → (0,1) → (0,2) → (1,2) → (2,2)
Example 2 — No Obstacles Needed
$ Input: grid = [[0,1,0,0,0],[1,1,0,1,0],[0,0,0,1,0]]
Output: 0
💡 Note: Path exists without removing obstacles: (0,0) → (0,2) → (0,3) → (0,4) → (1,4) → (2,4)
Example 3 — Minimum Grid
$ Input: grid = [[0,0],[0,0]]
Output: 0
💡 Note: Simple path from (0,0) → (0,1) → (1,1) with no obstacles

Constraints

  • m == grid.length
  • n == grid[i].length
  • 1 ≤ m, n ≤ 105
  • 2 ≤ m * n ≤ 105
  • grid[i][j] is either 0 or 1
  • grid[0][0] == grid[m - 1][n - 1] == 0

Visualization

Tap to expand
Minimum Obstacle Removal to Reach Corner INPUT 3x3 Grid (0=empty, 1=obstacle) 0 1 1 1 1 0 1 1 0 Start (0,0) End (2,2) grid = [[0,1,1], [1,1,0], [1,1,0]] Empty Obstacle ALGORITHM (0-1 BFS) 1 Initialize Deque Start at (0,0), cost=0 2 Process Cells Empty: add to front (cost+0) 3 Handle Obstacles Obstacle: add to back (cost+1) 4 Reach Target Return cost at (m-1, n-1) Deque State Example: [(0,0,0)] --> [(0,1,1),(1,0,1)] Optimal Path Found: (0,0) --> (0,1) --> (1,1) --> (2,2) Removed: (0,1) and (1,1) FINAL RESULT Optimal Path Visualization START X remove 1 1 X remove 0 1 1 END Output: 2 OK - Minimum obstacles removed to reach corner Key Insight: 0-1 BFS uses a deque to handle edge weights of 0 and 1 efficiently in O(m*n) time. Empty cells (weight 0) are added to the front of deque, obstacles (weight 1) to the back. This ensures cells are always processed in order of increasing cost - optimal for shortest path! TutorialsPoint - Minimum Obstacle Removal to Reach Corner | 0-1 BFS with Deque Approach
Asked in
Google 45 Amazon 38 Microsoft 32 Meta 28
68.0K Views
High Frequency
~35 min Avg. Time
2.2K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen