> For the complete documentation index, see [llms.txt](https://timmybeeflin.gitbook.io/cracking-leetcode/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://timmybeeflin.gitbook.io/cracking-leetcode/dfs-and-bfs/bfs/841.-keys-and-rooms.md).

# 841. Keys and Rooms

<pre><code><strong>BFS
</strong></code></pre>

```
T: O(n)
```

```
S: O(n)
```

````java
```java
class Solution {
    public boolean canVisitAllRooms(List<List<Integer>> rooms) {
        int n = rooms.size();
        Set<Integer> visited = new HashSet<>();
        Queue<Integer> queue = new LinkedList<>();
        queue.offer(0);

        while (!queue.isEmpty()) {
            int cur = queue.poll();
            if (visited.contains(cur)) {
                continue;
            }
            visited.add(cur);
            for (int next : rooms.get(cur)) {
                queue.offer(next);
            }
        }

        return visited.size() == n;
    }
}

/*
BFS
T: O(n)
S: O(n)

from to 

  0. 1.   2. 3
[[1],[2],[3],[]]

0 -> 1
1 -> 2
2 -> 3

   0.     1.    2.  3
[[1,3],[3,0,1],[2],[0]]



0 -> 1
     3

2 -> 2     

so we only need to know which room can't arrive...

*/
```
````
