Nearest Exit from Entrance in Maze — LeetCode 1926 Python Solution

MediumBreadth-First SearchArrayMatrix
Problem
#1926
Reading time
4 min

The problem

You are given an m x n matrix maze (0-indexed) with empty cells (represented as '.') and walls (represented as '+'). You are also given the entrance of the maze, where entrance = [entrancerow, entrancecol] denotes the row and column of the cell you are initially standing at.

Example

Input
maze = [["+","+",".","+"],[".",".",".","+"],["+","+","+","."]], entrance = [1,2]
Output
1
Explanation
There are 3 exits in this maze at [1,0], [0,2], and [2,3].

Python solution

Python
class Solution:
    def nearestExit(self, maze: List[List[str]], entrance: List[int]) -> int:
        m, n = len(maze), len(maze[0])
        i, j = entrance
        q = deque([(i, j)])
        maze[i][j] = "+"
        ans = 0
        while q:
            ans += 1
            for _ in range(len(q)):
                i, j = q.popleft()
                for a, b in [[0, -1], [0, 1], [-1, 0], [1, 0]]:
                    x, y = i + a, j + b
                    if 0 <= x < m and 0 <= y < n and maze[x][y] == ".":
                        if x == 0 or x == m - 1 or y == 0 or y == n - 1:
                            return ans
                        q.append((x, y))
                        maze[x][y] = "+"
        return -1

Complexity

MeasureComplexity
TimeO(m \times n)
SpaceO(m \times n) auxiliary

Pattern: Matrix and Grid

Treat a 2-D grid as a graph whose neighbours are the four adjacent cells. LeetCode 1926. Nearest Exit from Entrance in Maze is filed here because LeetCode tags it Matrix, which is the vocabulary this hub collects.

The matrix and grid guide has the Python template for the pattern and the 216 LeetCode problems that use it.

Related problems

On a study list

This problem is on LeetCode 75.

Frequently asked questions

How hard is LeetCode 1926. Nearest Exit from Entrance in Maze?
LeetCode 1926. Nearest Exit from Entrance in Maze is rated Medium on LeetCode.
What is the time complexity of LeetCode 1926. Nearest Exit from Entrance in Maze?
The Python solution on this page runs in O(m \times n).
What is the space complexity of LeetCode 1926. Nearest Exit from Entrance in Maze?
The Python solution on this page uses O(m \times n) auxiliary space.
What topics does LeetCode 1926. Nearest Exit from Entrance in Maze cover?
LeetCode 1926. Nearest Exit from Entrance in Maze is tagged Breadth-First Search, Array and Matrix on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview