SDE & MLE Prep

1926. Nearest Exit from Entrance in Maze

Problem

In the maze, '.' is open and '+' is a wall. Starting at entrance, moving up, down, left or right, return the fewest steps to the nearest exit: an open cell on the border other than the entrance itself. Return −1 if none is reachable.

Example: maze = ["++.+","...+","+++."], entrance = [1,2] → 1

BFS from the entrance; the first border empty cell reached (other than the entrance itself) is the nearest exit.

Complexity: O(R·C).

class Solution:
    def nearestExit(self, maze: List[List[str]], entrance: List[int]) -> int:
        R, C = len(maze), len(maze[0])
        start = tuple(entrance)
        seen, q, steps = {start}, deque([start]), 0
        while q:
            steps += 1
            for _ in range(len(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 maze[nr][nc] == "." and (nr, nc) not in seen:
                        if nr in (0, R - 1) or nc in (0, C - 1):
                            return steps
                        seen.add((nr, nc))
                        q.append((nr, nc))
        return -1