Leetcode 1926: Nearest Exit from Entrance in Maze

grid47
grid47
Exploring patterns and algorithms
Apr 28, 2024 6 min read

You are given a maze and need to find the nearest exit from the entrance. An exit is defined as an empty cell on the border of the maze. Return the shortest path to the nearest exit, or -1 if no exit is reachable.
Problem
Approach
Steps
Complexity
Input: The input consists of a maze represented as a 2D grid and the coordinates of the entrance.
Example: maze = [[".", ".", "+", "+"], [".", ".", ".", "+"], ["+", "+", ".", "."]], entrance = [1, 2]
Constraints:
• 1 <= m, n <= 100
• maze[i][j] is either '.' or '+'
• entrance will always be an empty cell
Output: Return the number of steps to the nearest exit, or -1 if no exit is reachable.
Example: 1
Constraints:
Goal: Find the shortest path from the entrance to any exit using breadth-first search (BFS).
Steps:
• Initialize a queue with the entrance cell.
• Use BFS to explore all possible moves from the entrance.
• Track visited cells to avoid reprocessing.
• Stop when an exit is found, or return -1 if no exit is reachable.
Goal: Handle mazes with varying sizes efficiently within the given constraint of 1 <= m, n <= 100.
Steps:
• The maze dimensions are at most 100x100.
• The entrance is always an empty cell.
Assumptions:
• The entrance is always an empty cell.
• You can only move in four directions: up, down, left, and right.
Input: maze = [[".", ".", "+", "+"], [".", ".", ".", "+"], ["+", "+", ".", "."]], entrance = [1, 2]
Explanation: The nearest exit is at [0, 2], which is 1 step away from the entrance at [1, 2].

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus