Data Structures & AlgorithmsVery hardProduct company OA

Problem: Each grid cell has an arrow; moving along a cell's arrow is free, moving in any other direction costs 1 (you change the arrow). Find the minimum cost from the top-left to the bottom-right cell with 0-1 BFS. What is printed (cost, number of cells reachable for free, largest finite distance)?

Problem: Each grid cell has an arrow; moving along a cell's arrow is free, moving in any other direction costs 1 (you change the arrow). Find the minimum cost from the top-left to the bottom-right cell with 0-1 BFS. What is printed (cost, number of cells reachable for free, largest finite distance)?
from collections import deque
g = ["RRD",
     "DLL",
     "RRU",
     "LRD"]
R, C = len(g), len(g[0])
dirs = {"R": (0, 1), "L": (0, -1), "D": (1, 0), "U": (-1, 0)}
dist = [[10**9] * C for _ in range(R)]; dist[0][0] = 0
dq = deque([(0, 0)])
while dq:
    r, c = dq.popleft()
    for ch, (dr, dc) in dirs.items():
        nr, nc = r + dr, c + dc
        if 0 <= nr < R and 0 <= nc < C:
            w = 0 if g[r][c] == ch else 1
            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], sum(row.count(0) for row in dist), max(max(r) for r in dist))
What is printed?
  1. A. 2 9 2
  2. B. 1 9 1
  3. C. 0 12 0
  4. D. 1 6 1

Correct answer: B. 1 9 1

Following the arrows from (0, 0) visits R, R, D, L, L, D, R, R and then U back into a loop, so the bottom row is never reached for free – 9 cells have cost 0. Changing one arrow (e.g. the U at (2, 2) to D) reaches the goal, so the answer is 1, and every cell of the last row is reachable with exactly one change. Weight-0 edges go to the deque front, weight-1 to the back: O(R·C).

More Coding Interview Problems questions

Exams that ask this topic