Problem Description
Given a grid represented by a 2D matrix where each cell is either empty (0) or an obstacle (1), the goal is to find the shortest path from the top-left corner (0,0) to the bottom-right corner (m-1, n-1) while being allowed to eliminate at most k obstacles along the way. If no valid path exists, return -1.
Key Insights
- Use a Breadth-First Search (BFS) approach to explore the grid level by level.
- Maintain a state that includes the current position (row and column) and the number of obstacles eliminated so far.
- Use a 3-dimensional visited data structure (or a 2D array with obstacle elimination count) to avoid reprocessing states that have been reached with fewer eliminations.
- The BFS ensures that the first time you reach the target, it is via the shortest path.
Space and Time Complexity
Time Complexity: O(m * n * k), where m and n are grid dimensions and k is the maximum obstacles that can be eliminated. Space Complexity: O(m * n * k), due to storing the state (position and obstacles eliminated).
Solution
The solution utilizes a modified BFS that tracks each state as a tuple (row, column, obstaclesEliminated). Starting from (0,0) with 0 obstacles eliminated, we explore all possible moves (up, down, left, right). When moving to an adjacent cell:
- If the cell is empty, continue without increasing the elimination count.
- If the cell is an obstacle and you have remaining eliminations (i.e., obstaclesEliminated < k), increase the elimination count. Only states that offer a better (i.e., lower elimination count) path to a cell compared to any previously recorded state are added to the BFS queue. This prevents unnecessary reprocessing and reduces time complexity. When the destination is reached, the current step count from the BFS is returned. If the queue depletes without reaching the destination, the function returns -1.