Leetcode Problem 1926. Nearest Exit from Entrance in Maze
1926. Nearest Exit from Entrance in Maze
Leetcode Solutions
Breadth First Search (BFS) for Nearest Exit in a Maze
Initialize a queue and add the entrance cell along with its distance (0) to the queue.
Mark the entrance cell as visited by changing its value in the maze to '+'.
While the queue is not empty, perform the following steps:
a. Dequeue the front cell from the queue and get its current distance.
b. Check all four possible directions (up, down, left, right) from the current cell.
c. For each direction, if the neighboring cell is within bounds, not a wall, and not visited:
i. If the neighboring cell is an exit (on the border and not the entrance), return the current distance + 1.
ii. Otherwise, mark the cell as visited and enqueue it with the distance incremented by 1.
If no exit is found after the BFS completes, return -1.