Data Structures & AlgorithmsVery hardProduct company OA

0-1 BFS on a grid: stepping into '#' costs 1 (a wall to break), stepping onto '.' or 'T' costs 0. What is the minimum number of walls to break from S (top-left) to T (bottom-right), and how many walls are there?

0-1 BFS on a grid: stepping into '#' costs 1 (a wall to break), stepping onto '.' or 'T' costs 0. What is the minimum number of walls to break from S (top-left) to T (bottom-right), and how many walls are there?
from collections import deque
grid = ["S.#..",
        "##.#.",
        "..#.#",
        ".#..T"]
R, C = len(grid), len(grid[0])
dist = [[10**9] * C for _ in range(R)]
dq = deque([(0, 0)]); dist[0][0] = 0
while dq:
    r, c = dq.popleft()
    for dr, dc in ((1, 0), (-1, 0), (0, 1), (0, -1)):
        nr, nc = r + dr, c + dc
        if 0 <= nr < R and 0 <= nc < C:
            w = 1 if grid[nr][nc] == "#" else 0
            if dist[r][c] + w < dist[nr][nc]:
                dist[nr][nc] = dist[r][c] + w
                (dq.append if w else dq.appendleft)((nr, nc))
print(dist[3][4], sum(row.count("#") for row in grid))
  1. A. 3 7
  2. B. 2 7
  3. C. 1 7
  4. D. 2 6

Correct answer: B. 2 7

Edges of weight 0 go to the FRONT of the deque and weight-1 edges to the back, so the deque always holds at most two distinct distances in order – Dijkstra's invariant in O(V + E) without a heap. Here S's free region and T's pocket {(2,3), (3,2), (3,3), T} are each sealed by walls, so at least 2 breaks are needed, and 2 suffice: break (0,2), walk free along the top row and down to (1,4), break (2,4) and step onto T. A plain BFS that counts steps instead of walls answers a different question.

More Trees, Graphs, Recursion and Dynamic Programming questions

Exams that ask this topic