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/0800-0899/0841.Keys and Rooms/README_EN.md
+131Lines changed: 131 additions & 0 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -213,4 +213,135 @@ impl Solution {
213
213
214
214
<!-- solution:end -->
215
215
216
+
<!-- solution:start -->
217
+
218
+
### Solution 2: BFS
219
+
220
+
We can also use the Breadth-First Search (BFS) method to traverse the entire graph. We use a hash table or an array `vis` to mark whether the current node has been visited to prevent repeated visits.
221
+
222
+
Specifically, we define a queue $q,ドル initially put node 0ドル$ into the queue, and then continuously traverse the queue. Each time we take out the front node $i$ of the queue, if $i$ has been visited, we skip it directly; otherwise, we mark it as visited, and then add the nodes that $i$ can reach to the queue.
223
+
224
+
Finally, we count the number of visited nodes. If it is the same as the total number of nodes, it means that all nodes can be visited; otherwise, it means that there are unreachable nodes.
225
+
226
+
The time complexity is $O(n + m),ドル and the space complexity is $O(n)$. Where $n$ is the number of nodes, and $m$ is the number of edges.
0 commit comments