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 freely1- 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
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.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code