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 Corner011110110StartEnd✓ 0: Empty cell (free move)✗ 1: Obstacle (costs 1 to remove)Optimal Path: (0,0) → (0,1) → (0,2) → (1,2) → (2,2)Obstacles removed: 2 (at positions (0,1) and (0,2))Result: 2 obstacles removed
Understanding the Visualization
1
Input Grid
2D grid with 0s (empty) and 1s (obstacles)
2
Find Path
Navigate from top-left to bottom-right
3
Count Removals
Return minimum obstacles removed
Key Takeaway
🎯 Key Insight: Use 0-1 BFS to prioritize free moves over obstacle removals for optimal pathfinding
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