Shortest Path in a Grid with Obstacles Elimination

Hard

Topics
ArrayBFSMatrix

grid holds 0 for an empty cell and 1 for an obstacle. You start at the top-left cell and want the bottom-right cell, moving up, down, left or right one step at a time.

You may remove at most k obstacles along the way. Return the fewest steps needed, or -1 if the finish cannot be reached.

Example 1

000011102000012
on the routeobstacle removed to use itobstacle left standing
4 steps and 1 removal reach the bottom-right cell of this 3 by 3 grid, out of 1 removal allowed. Arriving somewhere having spent a different number of removals is a genuinely different situation, because the one with more budget left can still afford obstacles ahead — so a cell is not simply visited or not. The second shade marks where the route went through an obstacle rather than around it.
Steps go up, down, left and right only, and each costs one whether or not an obstacle was removed.
Input:  grid = [[0,0,0],[1,1,0],[0,0,0]], k = 1
Output: 4
Explanation: Going down the right-hand column needs no removals and takes 4 steps.

Example 2

001111112100012
obstacle left standing
No route at all reaches the bottom-right cell of this 3 by 3 grid within the 1 removal allowed, so the answer is -1.
Input:  grid = [[0,1,1],[1,1,1],[1,0,0]], k = 1
Output: -1
Explanation: Any route needs at least two removals, and only one is allowed.

Example 3

00011001
on the routeobstacle left standing
The route shown needs no removal, so the budget goes entirely unused.
Input:  grid = [[0,0],[1,0]], k = 0
Output: 2
Explanation: With no removals permitted the route still exists, across the top and down.

Constraints

  • 1 <= grid.length, grid[0].length <= 40
  • grid[i][j] is 0 or 1
  • 1 <= k <= grid.length * grid[0].length
  • grid[0][0] == grid[m-1][n-1] == 0
Editorial — intuition, approach, complexity and pitfalls

Intuition

Without obstacle removal this is a plain ring-by-ring walk over cells. Removal breaks that, and the reason is worth being precise about: a cell is no longer either visited or not. Arriving at a cell having spent 2 removals is a different situation from arriving having spent 0, because the second leaves more options ahead.

So the thing being explored is not a cell, it is a pair: which cell, and how many removals used so far. Mark those pairs as visited rather than cells, and the ordinary ring-by-ring walk is correct again, because every step still costs exactly one.

This is the single mistake that sinks most attempts. Marking cells alone means the first arrival wins and later arrivals with a healthier removal budget are discarded, so a route that was briefly more expensive but cheaper overall is never found.

One refinement is worth knowing: arriving at a cell with more removals left than some earlier arrival is strictly better, so a budget worse than one already recorded for that cell can be dropped. Tracking the best remaining budget per cell is a smaller visited set than the full pair set and prunes the same branches.

Approach

  1. The state is (row, col, used) where used is the number of obstacles removed so far.
  2. Explore outward from (0, 0, 0) at distance 0, ring by ring, so the first arrival at the finish is the fewest steps.
  3. For each of the four neighbours, compute the new used: unchanged for an empty cell, one more for an obstacle.
  4. Discard the move when used would exceed k.
  5. Mark (row, col, used) visited rather than (row, col), or keep the best remaining budget per cell and discard any arrival that is no better.
  6. Return the distance when the finish is reached, and -1 if the exploration empties.

Walkthrough

grid = [[0,0,0],
        [1,1,0],
        [0,0,0]]
k = 1

the route that needs no removal
   (0,0) -> (0,1) -> (0,2) -> (1,2) -> (2,2)
   4 steps, used 0

there is also a route THROUGH an obstacle
   (0,0) -> (1,0) removes the obstacle, used 1
         -> (2,0) -> (2,1) -> (2,2)
   also 4 steps, used 1

both are 4, so the answer is 4

why the state must include `used`
   consider arriving at (1,2) two ways:
      from (0,2), used 0
      from (2,2), used 0
   same budget, so one can be discarded. But if a route
   arrived at (1,2) having used 1, and a cheaper-in-steps
   route arrived having used 0, discarding the second
   because the cell was "already visited" throws away the
   only route that can still afford an obstacle later.

grid = [[0,1,1],[1,1,1],[1,0,0]], k = 1
   every route from (0,0) to (2,2) crosses at least two
   obstacles, and only one removal is allowed
   answer -1

Complexity

  • Time — O(rows * cols * k): each cell is reachable with each of the k + 1 budgets, and each such state is expanded once.
  • Space — O(rows * cols * k): the visited set over states.

Common Pitfalls

  • Marking cells visited instead of cell-and-budget pairs. This is the central mistake and it silently returns a value that is too large, or -1.
  • Forgetting the single-cell grid, where the start is already the finish and the answer is 0.
  • Adding the obstacle cost of the cell you are leaving rather than the one you are entering.
  • Using a cost-ordered queue. Every step costs 1, so a plain ring-by-ring walk is already correct and simpler.
  • Allowing used to reach k + 1 before checking, which permits one removal too many.

Full Solution — all languages

class Solution:
    def shortestPath(self, grid, k):
        from collections import deque

        rows, cols = len(grid), len(grid[0])

        if rows == 1 and cols == 1:
            return 0

        # The state is (cell, removals used) -- NOT just the cell. Arriving
        # with a different budget is a genuinely different situation.
        seen = {(0, 0, 0)}
        queue = deque([(0, 0, 0, 0)])      # row, col, used, steps

        while queue:
            r, c, used, steps = queue.popleft()

            for dr, dc in ((1, 0), (-1, 0), (0, 1), (0, -1)):
                nr, nc = r + dr, c + dc
                if not (0 <= nr < rows and 0 <= nc < cols):
                    continue

                spent = used + grid[nr][nc]
                if spent > k:
                    continue

                if nr == rows - 1 and nc == cols - 1:
                    return steps + 1

                if (nr, nc, spent) not in seen:
                    seen.add((nr, nc, spent))
                    queue.append((nr, nc, spent, steps + 1))

        return -1
SensAI
Beta
Tap the mic to stop voice mode