ProgrammingHardTCS NQT · Accenture

What is printed?

What is printed?
from collections import deque
g = ['..#', '.##', '...']
def bfs(g):
    R, C = len(g), len(g[0])
    d = {(0, 0): 0}
    q = deque([(0, 0)])
    while q:
        r, c = q.popleft()
        for dr, dc in ((1, 0), (0, 1), (-1, 0), (0, -1)):
            nr, nc = r + dr, c + dc
            if 0 <= nr < R and 0 <= nc < C and g[nr][nc] == '.' and (nr, nc) not in d:
                d[(nr, nc)] = d[(r, c)] + 1
                q.append((nr, nc))
    return d.get((R - 1, C - 1), -1)
print(bfs(g))
  1. A. 3
  2. B. 5
  3. C. 4
  4. D. -1

Correct answer: C. 4

The only route runs down the left column and then right along the bottom row: (0,0) to (1,0) to (2,0) to (2,1) to (2,2), which is 4 steps. BFS finds the shortest one because each level is expanded before the next.

More Python Programming questions

Exams that ask this topic