Problem Description
Given a 2D grid where 0 represents an empty cell and 1 represents an obstacle, find the minimum number of obstacles to remove to travel from the upper-left corner (0, 0) to the lower-right corner (m - 1, n - 1). Movement is allowed in four directions: up, down, left, and right. The start and destination cells are guaranteed to be 0 (empty).
Key Insights
- The grid can be interpreted as a weighted graph where moving through an empty cell (0) has cost 0 and moving through an obstacle (1) has cost 1.
- The goal is to find the path with the minimum total cost.
- Use a 0-1 BFS or a modified Dijkstra's algorithm to efficiently process the grid.
- 0-1 BFS optimizes the traversal by using a deque: pushing 0-cost moves to the front and 1-cost moves to the back.
Space and Time Complexity
Time Complexity: O(m * n) since each cell is processed at most once. Space Complexity: O(m * n) for the deque and the visited/cost matrix.
Solution
We solve the problem by leveraging 0-1 BFS. The grid is modeled as a weighted graph where:
- Moving to a neighbor cell with value 0 has no additional cost.
- Moving to a neighbor cell with value 1 incurs a cost of 1 (obstacle removal).
A deque (double-ended queue) is used:
- When moving to an empty cell (0), push the new position to the front of the deque.
- When moving to an obstacle (1), push the new position to the back.
This ensures positions that cost 0 are prioritized, and we maintain an array or matrix to keep track of the minimum obstacles removed to reach each cell.
The algorithm terminates when the destination cell is dequeued with the minimum cost, or when all cells are processed.