AlgoInsight

DSA problem

Shortest Path in a Grid with Obstacles Elimination

HardBreadth First Search (BFS)Pattern: Breadth First Search (BFS)top300GoogleAmazonMicrosoftUberApple

You are given an m x n grid where each cell is either 0 (empty) or 1 (obstacle). You start at cell (0, 0) and want to reach the bottom-right cell (m - 1, n - 1). You may move 4-directionally to an adjacent empty cell. Additionally you have a quota: you may eliminate up to k obstacles along the way, walking through them as if they were empty cells. Return the minimum number of steps to reach the bottom-right corner, or -1 if it is impossible.

If k were always 0, this would be a plain BFS on a grid. The twist is that the state of "being at cell (r, c) with x eliminations remaining" is genuinely different from "being at (r, c) with y eliminations remaining" — the available futures depend on how many eliminations you still have.

Therefore the correct state space is the triple (r, c, k_left), where k_left is the number of obstacle eliminations still available. BFS over this expanded graph guarantees the shortest path. There are at most m * n * (k + 1) such states, so the algorithm is polynomial.

To prevent revisiting useless states, mark (r, c, k_left) as visited when enqueued. A common optimisation: if k >= m + n - 2 you can always walk diagonally through everything, so the answer is m + n - 2. This early-return short-circuits enormous k values. Otherwise BFS runs in O(m * n * k) time and space.

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 goes around or through one obstacle; the minimum number of cells walked is 6.
Example 2
Input: grid = [[0,1,1],[1,1,1],[1,0,0]], k = 1
Output: -1
Explanation: Even with one elimination, the obstacles cannot all be bypassed to reach the goal.
Example 3
Input: grid = [[0,0],[0,0]], k = 0
Output: 2
Explanation: No obstacles; the straight path of length 2 reaches the corner.

Constraints

3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.

bfsgridshortest-pathstate-space-search

Browse all DSA problems