Data Structures & AlgorithmsModerateTCS NQT · BFS warm-up

Problem: How many cells of a 3 x 3 grid are at exactly 2 steps (4-directional moves, no obstacles) from the top-left cell? Run the BFS below.

Problem: How many cells of a 3 x 3 grid are at exactly 2 steps (4-directional moves, no obstacles) from the top-left cell? Run the BFS below.
from collections import deque
def cnt(n, m, s, k):
    d = {s: 0}
    q = deque([s])
    while q:
        x, y = q.popleft()
        for dx, dy in ((1, 0), (-1, 0), (0, 1), (0, -1)):
            nx, ny = x + dx, y + dy
            if 0 <= nx < n and 0 <= ny < m and (nx, ny) not in d:
                d[(nx, ny)] = d[(x, y)] + 1
                q.append((nx, ny))
    return sum(1 for v in d.values() if v == k)
print(cnt(3, 3, (0, 0), 2))
What is printed?
  1. A. 2
  2. B. 3
  3. C. 4
  4. D. 5

Correct answer: B. 3

Cells at Manhattan distance 2 from (0,0) are (2,0), (1,1) and (0,2). Diagonal moves would add cells and change the answer.

More Coding Interview Problems questions

Exams that ask this topic