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

  1. Initialize a queue and add the entrance cell along with its distance (0) to the queue.
  2. Mark the entrance cell as visited by changing its value in the maze to '+'.
  3. 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.
  4. If no exit is found after the BFS completes, return -1.
UML Thumbnail

Ask Question

Programming Language
image/screenshot of info(optional)
Full Screen
Loading...

Suggested Answer

Answer
Full Screen
Copy Answer Code
Loading...