download

Grid BFS with one wall break returns -1. Why?

Algorithms~15 minReviewed 3 Dec 2026Free · No sign-in

Question

A robot walks a grid of . (open) and # (wall) from top-left (0, 0) to bottom-right (rows - 1, cols - 1) (both .), moving up, down, left, or right. It may break at most k walls.

On the 3x5 grid below with k = 1, the exit is reachable in 8 steps, yet the BFS below returns -1. Find the bug, explain which cell gets blocked, and fix shortest_path(grid, k).

"PYTHON"
grid = [".#...", "...##", "####."]
"CODE · PYTHON"
from collections import deque


def shortest_path(grid, k):
    rows, cols = len(grid), len(grid[0])
    queue, seen = deque([(0, 0, k, 0)]), {(0, 0)}
    while queue:
        r, c, rem, steps = queue.popleft()
        if (r, c) == (rows - 1, cols - 1):
            return steps
        for nr, nc in ((r + 1, c), (r - 1, c), (r, c + 1), (r, c - 1)):
            if 0 <= nr < rows and 0 <= nc < cols and (nr, nc) not in seen:
                nrem = rem - (grid[nr][nc] == "#")
                if nrem >= 0:
                    seen.add((nr, nc))
                    queue.append((nr, nc, nrem, steps + 1))
    return -1


print(shortest_path([".#...", "...##", "####."], 1))  # -1, should be 8
Show hints (3)
  1. "TRACE CELL (0, 2)"

    Compare two ways to reach (0, 2): straight right through wall (0, 1), or around row 1 without breaking any wall. Which arrives first, and how many breaks does each have left?

  2. "POSITION IS NOT STATE"

    Plain grid BFS only needs (r, c) because every arrival has the same future moves. Here, arriving at (0, 2) with rem = 1 can cross (1, 4), while rem = 0 cannot.

  3. "INCLUDE REMAINING BUDGET"

    Store (r, c, rem) in seen (or track the highest rem seen at each (r, c) and revisit only when nrem is strictly higher).

Show checked explanation

Tracking only (r, c) in seen treats two arrivals with different remaining wall breaks as the same state. The shortcut through (0, 1) reaches (0, 2) at step 2 with 0 breaks left and locks out the 4-step detour that arrives with 1 break left needed for wall (1, 4). Key seen on (r, c, rem) instead.

"SOLUTION · PYTHON"
from collections import deque


def shortest_path(grid, k):
    rows, cols = len(grid), len(grid[0])
    queue, seen = deque([(0, 0, k, 0)]), {(0, 0, k)}
    while queue:
        r, c, rem, steps = queue.popleft()
        if (r, c) == (rows - 1, cols - 1):
            return steps
        for nr, nc in ((r + 1, c), (r - 1, c), (r, c + 1), (r, c - 1)):
            if 0 <= nr < rows and 0 <= nc < cols:
                nrem = rem - (grid[nr][nc] == "#")
                if nrem >= 0 and (nr, nc, nrem) not in seen:
                    seen.add((nr, nc, nrem))
                    queue.append((nr, nc, nrem, steps + 1))
    return -1


print([shortest_path([".#...", "...##", "####."], k) for k in (1, 2, 0)])
"OUTPUT"
[8, 6, -1]

Code and edge cases run on CPython 3.12.10; official documentation links checked. Checked by an editor other than the author.

Walkthrough

In plain grid BFS (such as flooding a warehouse from multiple leaks), every visit to (r, c) has identical future moves, so the first visit always wins. Here, the remaining budget rem changes which walls you can cross later. That makes the true search node (r, c, rem), not (r, c).

Look at grid = [".#...", "...##", "####."] with k = 1:

route to (0, 2)steps to (0, 2)rem leftcan break (1, 4)?total steps
(0,0) -> (0,1)# -> (0,2)20no (dead end)none
(0,0) -> (1,0) -> (1,1) -> (1,2) -> (0,2)41yes (breaks (1, 4))8

The starter marks (0, 2) visited at step 2 with rem = 0. That branch walks to (0, 4) at step 4 and dies at wall (1, 4) because it spent its only break on (0, 1). Meanwhile, the clean detour reaches (0, 2) at step 4 with rem = 1 intact, gets rejected because (0, 2) in seen, and the search returns -1.

Keying seen on (r, c, rem) fixes it. State (0, 2, 0) and state (0, 2, 1) are distinct nodes, so the detour continues through (0, 3) -> (0, 4) -> (1, 4)# -> (2, 4) and finishes in 8 steps. With k = 2, the robot breaks both (0, 1) and (1, 4) in 6 steps. With k = 0, no route can enter (2, 4), returning -1.

You can prune even tighter by storing best_rem[(r, c)] instead of a 3-tuple set. Because BFS pops states in step order, any later arrival at (r, c) with nrem <= best_rem[(r, c)] is no better and can be skipped. Both versions run in O(R * C * (k + 1)) worst-case time; best_rem cuts the visited table from O(R * C * (k + 1)) to O(R * C).

Common mistakes

  • Marking (r, c) visited without rem. Any early path that burns its break blocks a slightly longer path that saved its break for a later mandatory wall.
  • Marking a state in seen when popping instead of when pushing. The same (r, c, rem) gets queued from multiple neighbours, blowing up queue size and runtime.
  • Skipping the nrem >= 0 check before marking seen or queueing. Entering a wall with rem = 0 gives nrem = -1 and lets the robot walk through walls.
  • Ignoring large k. When k >= rows + cols - 3 (with open start and goal), the robot can walk any Manhattan shortest path directly in rows + cols - 2 steps without running BFS.

Follow-up questions

  • "Why does keeping only best_rem[(r, c)] never drop a valid shortest path?" BFS visits states in non-decreasing step order. If a path reached (r, c) earlier with at least as many breaks left, it is both no slower and at least as capable for every remaining move. So a later arrival with nrem <= best_rem[(r, c)] can never beat it.
  • "What if breaking a wall costs 2 steps instead of 1?" Steps are no longer uniform, so plain BFS can pop a longer-cost state first. Switch to Dijkstra's algorithm with heapq keyed by (cost, r, c, rem), keeping the same state-space idea.
  • "How does this pattern extend to collecting keys to open locked doors?" Replace rem with a bitmask keys of collected keys, making each state (r, c, keys). With m keys, there are R * C * 2^m states, and BFS still finds the fewest steps.

What a strong answer covers

Explains why (r, c) loses state whenever remaining budget restricts future moves. Traces (0, 2) at step 2 versus step 4, fixes seen to (r, c, rem), and mentions best_rem pruning plus the k >= R + C - 3 shortcut.

Open in interactive practice deck →

Original OfferVibe question. NIST DADS: breadth-first search · Python collections.deque.
© 2026 OfferVibe · Text CC BY-NC-SA 4.0 · code MITFree to share and adapt with credit, not for commercial use. Code samples are free for any use.