Shortest Grid Path with Obstacle Eliminations
MercorSoftware Engineer · Technical ScreenLast updated
This question tests your ability to apply Breadth-First Search (BFS) on an augmented state space where path state includes both coordinates and remaining resources.
Shortest Grid Path with Obstacle Eliminations
You are given an m x n integer grid grid where each cell is either 0 (empty) or 1 (obstacle). You are also given an integer k representing the maximum number of obstacles you are allowed to eliminate.
You start at the top-left corner (0, 0) and want to reach the bottom-right corner (m - 1, n - 1). In each step, you can move one cell up, down, left, or right, provided the target cell is within the grid boundaries.
Return the minimum number of steps needed to walk from (0, 0) to (m - 1, n - 1). If it is impossible to reach the destination after eliminating at most k obstacles, return -1.
Function Signature
def shortest_path(grid: list[list[int]], k: int) -> int:
pass
Examples
Example 1:
Input: grid = [
[0, 0, 0],
[1, 1, 0],
[0, 0, 0],
[0, 1, 1],
[0, 0, 0]
], k = 1
Output: 6
Explanation:
The shortest path without eliminating any obstacles takes 10 steps. By eliminating the obstacle at (1, 0) or (3, 1), you can reach the bottom-right corner in 6 steps: (0,0) -> (1,0) [eliminate] -> (2,0) -> (3,0) -> (4,0) -> (4,1) -> (4,2).
Example 2:
Input: grid = [
[0, 1, 1],
[1, 1, 1],
[1, 0, 0]
], k = 1
Output: -1
Explanation:
We need to eliminate at least 2 obstacles to reach the bottom-right corner, but k = 1, so it is impossible.
Constraints
m == len(grid)n == len(grid[0])1 <= m, n <= 401 <= k <= m * ngrid[i][j]is either0or1.grid[0][0] == grid[m - 1][n - 1] == 0
Edge Cases to Consider
- The grid consists of a single cell
(1 x 1). kis sufficiently large (e.g.,k >= (m - 1) + (n - 1)), meaning you can take the direct Manhattan path regardless of obstacles.- Paths where revisiting a cell is beneficial only because you arrive with more remaining obstacle eliminations.
Hints
Hint 1
Since every step has uniform cost, Breadth-First Search (BFS) is the ideal algorithm to find the shortest path.
Hint 2
Model your BFS state as a tuple (row, col, remaining_k) rather than just (row, col).
Hint 3
To optimize visited checks, track the maximum remaining eliminations seen so far at each (row, col) rather than tracking every visited tuple.
Follow-up questions
- How can you optimize early termination if k is greater than or equal to the Manhattan distance between the start and destination?
- How would your approach change if eliminating an obstacle incurred an extra cost/weight instead of consuming a bounded count?
- If the grid dimensions were much larger (e.g., 1000 x 1000) and k was small, how could you optimize memory and search space?
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.