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?- A. 2
- B. 4
- C. 6
- 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
- Array c = [1, 2, 3, 0, 3, 3, 0, 6]. In how many ways can it be split into three non-empty contiguous parts whose sums are all equal? Run…
- Array d = [1, 2, 1, 3, 4, 3, 5]. Count the contiguous subarrays containing exactly three distinct values. Run the brute-force code. python…
- Houses have values e = [2, 7, 9, 3, 1, 8, 4, 6] and a robber cannot take two adjacent houses. Find the maximum sum that can be taken…
- Count the subarrays of v = [4, 6, 2, 1, 7, 3, 5, 1] whose XOR equals 0, considering only subarrays of length at least 3. Brute-force all…
- Histogram bars have heights h = [2, 1, 5, 6, 2, 3]. What is the area of the largest rectangle that fits entirely inside the histogram…
- What is the maximum sum of a non-empty subarray in the circular array [8, -8, 9, -9, 10, -11, 12], where the subarray may wrap from the…