Data Structures & AlgorithmsModerateProduct Company SDE · Amazon/Microsoft-style OA

Problem: Each cell of a grid holds 0 (empty) or 1. Return a grid of the distance from each cell to its nearest 0.

Problem: Each cell of a grid holds 0 (empty) or 1. Return a grid of the distance from each cell to its nearest 0.
from collections import deque
def near0(g):
    R, C = len(g), len(g[0])
    d = [[-1] * C for _ in range(R)]; q = deque()
    for r in range(R):
        for c in range(C):
            if g[r][c] == 0: d[r][c] = 0; q.append((r, c))
    while q:
        r, c = q.popleft()
        for nr, nc in ((r+1, c), (r-1, c), (r, c+1), (r, c-1)):
            if 0 <= nr < R and 0 <= nc < C and d[nr][nc] == -1:
                d[nr][nc] = d[r][c] + 1; q.append((nr, nc))
    return d
print(near0([[1, 1, 1], [1, 1, 1], [1, 1, 0]])[0])
What is the first row printed?
  1. A. [2, 2, 2]
  2. B. [4, 3, 3]
  3. C. [4, 3, 2]
  4. D. [3, 2, 1]

Correct answer: C. [4, 3, 2]

Multi-source BFS from every 0 at once gives each cell its Manhattan-style grid distance to the nearest 0 in O(R·C). The only 0 is at (2,2): row 0 is at distances 4, 3, 2. Running a separate BFS from every 1 would be O((R·C)²).

More Coding Interview Problems questions

Exams that ask this topic