Data Structures & AlgorithmsVery hardProduct Company SDE · ICPC regional

A 4×4 grid has rows "..#.", ".##.", "##.#", "#...". Entering a cell costs 1 if it is '#' and 0 otherwise, and you may move in four directions from the top-left to the bottom-right cell. Run the 0-1 BFS below. What is the minimum total cost?

A 4×4 grid has rows "..#.", ".##.", "##.#", "#...". Entering a cell costs 1 if it is '#' and 0 otherwise, and you may move in four directions from the top-left to the bottom-right cell. Run the 0-1 BFS below. What is the minimum total cost?
from collections import deque
g=["..#.",".##.","##.#","#..."]
R_,C_=len(g),len(g[0])
INF=10**9
dist=[[INF]*C_ for _ in range(R_)]
dist[0][0]=0; dq=deque([(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 g[nr][nc]=='#' else 0
            if dist[r][c]+w<dist[nr][nc]:
                dist[nr][nc]=dist[r][c]+w
                (dq.appendleft if w==0 else dq.append)((nr,nc))
print(dist[R_-1][C_-1])
What is printed?
  1. A. 2
  2. B. 4
  3. C. 6
  4. D. 3

Correct answer: A. 2

0-1 BFS with a deque processes zero-cost moves first, so the first arrival is optimal. Charging the cell being left instead of the cell entered is a different cost model, charging every move one unit ignores the free cells, and inverting the costs makes the free cells expensive.

More Coding Interview Problems questions

Exams that ask this topic