2290. Minimum Obstacle Removal to Reach Corner
Difficulty: Hard
Topics: Array, Breadth-First Search, Graph, Heap (Priority Queue), Matrix, Shortest Path
You are given a 0-indexed 2D integer array grid of size m x n. Each cell has one of two values:
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).
Example 1:
Example 2:
Constraints:
Hint:
Solution:
We need to model this problem using a graph where each cell in the grid is a node. The goal is to navigate from the top-left corner (0, 0) to the bottom-right corner (m-1, n-1), while minimizing the number of obstacles (1s) we need to remove.
Graph Representation:
Algorithm Choice:
0-1 BFS:
Let's implement this solution in PHP: 2290. Minimum Obstacle Removal to Reach Corner
Explanation:
Input Parsing:
- The grid is taken as a 2D array.
- Rows and columns are calculated for bounds checking.
Deque Implementation:
- SplDoublyLinkedList is used to simulate the deque. It supports adding elements at the front (unshift) or the back (push).
Visited Array:
- Keeps track of cells already visited to avoid redundant processing.
0-1 BFS Logic:
- Start from (0, 0) with a cost of 0.
- For each neighboring cell:
- If it's empty (grid[nx][ny] == 0), add it to the front of the deque with the same cost.
- If it's an obstacle (grid[nx][ny] == 1), add it to the back of the deque with an incremented cost.
Return the Result:
- When the bottom-right corner is reached, return the cost.
- If no valid path exists (though the problem guarantees one), return -1.
Complexity:
This implementation works efficiently within the given constraints.
Contact Links
If you found this series helpful, please consider giving the repository a star on GitHub or sharing the post on your favorite social networks ?. Your support would mean a lot to me!
If you want more helpful content like this, feel free to follow me:
The above is the detailed content of Minimum Obstacle Removal to Reach Corner. For more information, please follow other related articles on the PHP Chinese website!