Python coding

Fewest walls to break through

A grid is a non-empty list of equal-length strings where "." is open floor and "#" is a wall. You start at the top-left cell and want to reach the bottom-right cell, moving one cell up, down, left or right at a time. You may step into a wall cell only after breaking that wall. Return the fewest walls you must break.

The top-left and bottom-right cells are always open. A grid of one cell needs no breaks.

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

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

Each cell is a node. Stepping onto a wall costs 1 and onto floor costs 0: you want the cheapest route, not the one with fewest steps.

Hint 2

With only 0 and 1 weights, use 0-1 BFS: a deque where a free step goes to the front and a break goes to the back.

Solution and why it works
pythonO(rows·cols) · O(rows·cols)
from collections import deque


def fewest_breaks(grid: list[str]) -> int:
    rows, cols = len(grid), len(grid[0])
    cost = [[float("inf")] * cols for _ in range(rows)]
    cost[0][0] = 0
    dq = deque([(0, 0)])
    while dq:
        r, c = dq.popleft()
        for nr, nc in ((r + 1, c), (r - 1, c), (r, c + 1), (r, c - 1)):
            if 0 <= nr < rows and 0 <= nc < cols:
                w = 1 if grid[nr][nc] == "#" else 0
                if cost[r][c] + w < cost[nr][nc]:
                    cost[nr][nc] = cost[r][c] + w
                    if w:
                        dq.append((nr, nc))          # one more break: back of the line
                    else:
                        dq.appendleft((nr, nc))      # free step: same cost, front
    return cost[rows - 1][cols - 1]

Breaking a wall is an edge of weight 1 and walking on floor one of weight 0, so this is a shortest path with 0/1 weights. 0-1 BFS keeps the deque sorted by cost: a free step joins the front at the same cost, a break joins the back at cost + 1. It does Dijkstra's job in linear time, without a heap. Traps: plain BFS minimizes steps, not breaks; a right/down-only DP misses routes that wind up or left; re-sweeping the grid until nothing changes is quadratic.