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 = [entrance_row, entrance_col] is the row and column of the cell you are initially standing in.
In one step, you can move one cell up, down, left or right. You cannot step into a cell with a wall, and you cannot step outside the maze. Your goal is to find the nearest exit from the entrance. An exit is an empty cell on the border of the maze. The entrance does not count as an exit.
Return the number of steps in the shortest path from the entrance to the nearest exit, or -1 if no such path exists.
Function Signature
def nearest_exit(maze: list[list[str]], entrance: list[int]) -> int:
Rules
-
maze
is a list of rows, and each cell is the one-character string
'.'
or
'+'
.
-
A border cell is any cell in row
0
, row
m - 1
, column
0
or column
n - 1
.
-
The entrance is never an exit, even when it lies on the border.
Constraints
-
maze.length == m
-
maze[i].length == n
-
1 <= m, n <= 100
-
maze[i][j]
is either
'.'
or
'+'
-
entrance.length == 2
-
0 <= entrance_row < m
-
0 <= entrance_col < n
-
entrance
is always an empty cell
Examples
Input: maze = [["+","+",".","+"],[".",".",".","+"],["+","+","+","."]], entrance = [1, 2]
Output: 1
+ + . +
. . E +
+ + + .
E marks the entrance at [1, 2]. The exit at [0, 2] is 1 step up. The exit at [1, 0] is 2 steps away, and the empty border cell at [2, 3] cannot be reached because walls surround it.
Input: maze = [["+","+","+"],[".",".","."],["+","+","+"]], entrance = [1, 0]
Output: 2
The entrance at [1, 0] is on the border but does not count. The nearest exit is [1, 2], 2 steps to the right.
Input: maze = [[".","+"]], entrance = [0, 0]
Output: -1
The entrance is the only empty cell. It is on the border but is not an exit, and its only neighbor inside the maze is a wall, so no exit is reachable.