You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardexpand all lines: solution/1900-1999/1926.Nearest Exit from Entrance in Maze/README_EN.md
+34-33
Original file line number
Diff line number
Diff line change
@@ -80,7 +80,15 @@ Thus, the nearest exit is [1,2], which is 2 steps away.
80
80
81
81
<!-- solution:start -->
82
82
83
-
### Solution 1
83
+
### Solution 1: BFS
84
+
85
+
We can start from the entrance and perform a breadth-first search (BFS). Each time we reach a new empty cell, we mark it as visited and add it to the queue until we find an empty cell on the boundary, then return the number of steps.
86
+
87
+
Specifically, we define a queue $q$, initially adding $\textit{entrance}$ to the queue. We define a variable $\textit{ans}$ to record the number of steps, initially set to $1$. Then we start the BFS. In each round, we take out all elements from the queue and traverse them. For each element, we try to move in four directions. If the new position is an empty cell, we add it to the queue and mark it as visited. If the new position is an empty cell on the boundary, we return $\textit{ans}$. If the queue is empty, we return $-1$. After this round of search, we increment $\textit{ans}$ by one and continue to the next round of search.
88
+
89
+
If we finish the traversal without finding an empty cell on the boundary, we return $-1$.
90
+
91
+
The time complexity is $O(m \times n)$, and the space complexity is $O(m \times n)$. Here, $m$ and $n$ are the number of rows and columns in the maze, respectively.
0 commit comments