Python coding

Fewest steps, breaking up to k walls

A maze is a non-empty list of equal-length strings where "." is open and "#" is a wall. You start at the top-left cell and want the bottom-right one, moving one step up, down, left or right. You may break through at most k walls on the way: stepping into a wall breaks it and uses up one of your k breaks. Return the fewest steps to reach the exit, or -1 if it can't be done.

The start and exit cells are always open, and k ≥ 0.

Besides the tests, one large input (a 12 × 12 maze) with a ~100 ms limit (scaled to your device's speed): brute force won't pass.

  • fewest_steps_breaking(["..#","#.#","..."], 1) → 4
  • fewest_steps_breaking([".#.","##.","##."], 0) → -1
  • fewest_steps_breaking([".##","###","##."], 2) → -1
Ctrl/⌘ + Enter runs · Tab indents
Hint 1

Every step costs one, so BFS gives the fewest steps. But the cell alone isn't enough state: arriving with breaks to spare is not the same as arriving with none.

Hint 2

Make each node (row, col, breaks_left) and mark that triple visited when you queue it. Stepping into a wall needs breaks_left > 0 and lowers it by one.

Hint 3

The first time the exit comes off the queue, with however many breaks left, its distance is the answer.

Solution and why it works
pythonO(R·C·k), R × C = grid size · O(R·C·k)
from collections import deque


def fewest_steps_breaking(grid: list[str], k: int) -> int:
    rows, cols = len(grid), len(grid[0])
    queue, seen = deque([(0, 0, k, 0)]), {(0, 0, k)}
    while queue:
        r, c, left, dist = queue.popleft()
        if (r, c) == (rows - 1, cols - 1):
            return dist
        for nr, nc in ((r + 1, c), (r - 1, c), (r, c + 1), (r, c - 1)):
            if 0 <= nr < rows and 0 <= nc < cols:
                after = left - (grid[nr][nc] == "#")   # a wall spends one break
                if after >= 0 and (nr, nc, after) not in seen:
                    seen.add((nr, nc, after))         # the state, not just the cell
                    queue.append((nr, nc, after, dist + 1))
    return -1

BFS over states, not cells: a node is (row, col, breaks left), so the graph has R·C·(k + 1) nodes and each is queued once. The trap is a visited set of cells only: a short route that spends its breaks early marks a cell first and blocks a longer route that saved a break for the one wall that matters, so the answer comes out too long or -1. Trying every set of up to k walls with a plain BFS for each is correct but combinatorial.