Data Structures & AlgorithmsModerateTCS NQT Digital · Product Company SDE

Problem: Return the number of steps to reach the exit of a maze grid ('.' open, '+' wall) from an entrance, where an exit is an open border cell other than the entrance.

Problem: Return the number of steps to reach the exit of a maze grid ('.' open, '+' wall) from an entrance, where an exit is an open border cell other than the entrance.
from collections import deque
def nearest_exit(m, start):
    R, C = len(m), len(m[0]); q = deque([(*start, 0)]); seen = {tuple(start)}
    while q:
        r, c, d = q.popleft()
        if (r, c) != tuple(start) and (r in (0, R - 1) or c in (0, C - 1)): return d
        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 m[nr][nc] == '.' and (nr, nc) not in seen:
                seen.add((nr, nc)); q.append((nr, nc, d + 1))
    return -1
print(nearest_exit(["++.+", "...+", "+++."], [1, 2]), nearest_exit(["++", "+."], [1, 1]))
What is printed?
  1. A. 1 -1
  2. B. 2 -1
  3. C. 1 0
  4. D. 3 -1

Correct answer: A. 1 -1

BFS returns the first border cell reached, excluding the entrance itself. From (1, 2), moving up to (0, 2) reaches the border in 1 step. In the second maze the only open cell is the entrance, so there is no exit → −1 (returning 0 would wrongly count the entrance). O(R·C).

More Coding Interview Problems questions

Exams that ask this topic