Data Structures & AlgorithmsModerateTCS NQT · BFS warm-up

Problem: Starting at (0,0) in the grid below, how many cells are reachable by 4-directional moves through '.' cells? Run the BFS.

Problem: Starting at (0,0) in the grid below, how many cells are reachable by 4-directional moves through '.' cells? Run the BFS.
from collections import deque
g = ['..#', '.#.', '...']
seen = {(0, 0)}
q = deque([(0, 0)])
while q:
    x, y = q.popleft()
    for a, b in ((x + 1, y), (x - 1, y), (x, y + 1), (x, y - 1)):
        if 0 <= a < 3 and 0 <= b < 3 and g[a][b] == '.' and (a, b) not in seen:
            seen.add((a, b))
            q.append((a, b))
print(len(seen))
What is printed?
  1. A. 9
  2. B. 5
  3. C. 7
  4. D. 6

Correct answer: C. 7

BFS from (0,0) reaches all 7 open cells: the walls at (0,2) and (1,1) do not cut off (1,2), which is entered from (2,2). Counting every cell including walls gives 9, reporting the BFS distance to the farthest cell gives 5, and allowing only right/down moves misses (1,2) and gives 6.

More Coding Interview Problems questions

Exams that ask this topic