Minimum Obstacle Removal to Reach Corner - Problem
Navigate Through a Grid Maze: You're given a rectangular grid where you need to find the shortest path from the top-left corner to the bottom-right corner. However, this isn't just any ordinary pathfinding problem!

Each cell in the grid contains either:

  • 0 - An empty cell you can walk through freely
  • 1 - An obstacle that blocks your path, but can be removed at a cost

You can move in four directions: up, down, left, right. The challenge is to find the minimum number of obstacles you need to remove to create a path from (0,0) to (m-1,n-1).

Goal: Return the minimum number of obstacles that must be removed to reach the destination.

Input & Output

example_1.py โ€” Basic 3x3 Grid
$ 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). This requires removing 2 obstacles total.
example_2.py โ€” All Empty Cells
$ Input: grid = [[0,0,0],[0,0,0],[0,0,0]]
โ€บ Output: 0
๐Ÿ’ก Note: We can reach the destination without removing any obstacles. One possible path: (0,0) โ†’ (0,1) โ†’ (0,2) โ†’ (1,2) โ†’ (2,2).
example_3.py โ€” Single Path Through Obstacles
$ Input: grid = [[0,1,0,0,0],[0,1,0,1,0],[0,0,0,1,0]]
โ€บ Output: 1
๐Ÿ’ก Note: The optimal path removes only 1 obstacle at (2,3): (0,0) โ†’ (1,0) โ†’ (2,0) โ†’ (2,1) โ†’ (2,2) โ†’ (2,3) โ†’ (2,4). Only the obstacle at (2,3) needs to be removed.

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
Construction Site GridSTARTENDClear PathBarrier0-1 BFS Strategy:1. Free moves โ†’ Front of deque2. Barrier moves โ†’ Back of deque3. Always process min cost first4. Guaranteed optimal solution
Understanding the Visualization
1
Start at entrance
Begin at top-left corner (0,0) with 0 obstacles removed
2
Smart exploration
Use 0-1 BFS: free paths get higher priority (front of deque)
3
Cost tracking
Obstacle paths get lower priority (back of deque)
4
Optimal guarantee
First time reaching destination gives minimum obstacles
5
Efficient processing
Each cell visited at most once due to optimal substructure
Key Takeaway
๐ŸŽฏ Key Insight: Since we only have two costs (0 and 1), 0-1 BFS with a deque is more efficient than general Dijkstra's algorithm, achieving optimal O(mn) time complexity.
Asked in
Google 45 Amazon 38 Meta 22 Microsoft 31
52.3K Views
Medium-High Frequency
~25 min Avg. Time
1.8K 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