Skip to content

Practice Nearest Exit from Entrance in Maze

Read the task, work through the examples, and check your approach against the constraints. Use the original LeetCode task for coding and submissions.

Medium#1926
LeetCode Problem

Nearest Exit from Entrance in Maze

Problem Statement

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. 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 defined as an empty cell that is at 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.

Source: Nearest Exit from Entrance in Maze on LeetCode. Use the original task for its coding environment and submissions.

Examples

# Example 1

Input
maze = [["+","+",".","+"],[".",".",".","+"],["+","+","+","."]], entrance = [1,2]
Output
1

# Example 2

Input
maze = [["+","+","+"],[".",".","."],["+","+","+"]], entrance = [1,0]
Output
2

# Example 3

Input
maze = [[".","+"]], entrance = [0,0]
Output
-1

Constraints

maze.length == m
maze[i].length == n
1 <= m, n <= 100
maze[i][j] is either '.' or '+'.
entrance.length == 2
0 <= entrancerow < m
0 <= entrancecol < n
entrance will always be an empty cell.

Related LeetCode Problems

Practice more problems similar to Nearest Exit from Entrance in Maze.

Review your practice with PhantomCodeAI

After trying the problem yourself, use the app to discuss your approach, complexity, and edge cases.