Keys and Rooms (LeetCode 841): Solution and Explanation
There are n rooms and only room 0 is open. Each room holds keys to other rooms. Return true if, starting from room 0 and collecting every key you find, you can enter every room.
Intuition
A key to room j found in room i lets you go from i to j, which is exactly a directed edge i -> j. The rooms and keys form a directed graph.
Being able to visit every room means every node is reachable from node 0. That is a plain graph search: DFS or BFS from 0.
Mark a room as seen the moment you get its key, not when you walk in. Then each room is pushed at most once, and duplicate keys are skipped right away.
Approach: DFS with an explicit stack
- Start with
seen = {0}andstack = [0]. - While the stack is not empty, pop a room.
- For each key in that room, if
keyis not inseen, add it toseenand push it. - When the stack is empty, return
len(seen) == len(rooms).
Step-by-step example
rooms = [[1,3],[3,0,1],[2],[0]]
- Pop room 0. Its keys 1 and 3 open new rooms, so seen = {0,1,3} and the stack is [1,3].
- Pop room 3. Its only key is 0, which is already seen, so nothing changes.
- Pop room 1. Keys 3, 0 and 1 are all already seen, so nothing is pushed.
- The stack is empty with 3 of 4 rooms seen. Room 2's only key is inside room 2, so the answer is false.
Code: Python, Java, C++
1class Solution:
2 def canVisitAllRooms(self, rooms: List[List[int]]) -> bool:
3 seen = {0}
4 stack = [0]
5 while stack:
6 room = stack.pop()
7 for key in rooms[room]:
8 if key not in seen:
9 seen.add(key)
10 stack.append(key)
11 return len(seen) == len(rooms)1class Solution {
2 public boolean canVisitAllRooms(List<List<Integer>> rooms) {
3 boolean[] seen = new boolean[rooms.size()];
4 seen[0] = true;
5 Deque<Integer> stack = new ArrayDeque<>();
6 stack.push(0);
7 int count = 1;
8 while (!stack.isEmpty()) {
9 int room = stack.pop();
10 for (int key : rooms.get(room)) {
11 if (!seen[key]) {
12 seen[key] = true;
13 count++;
14 stack.push(key);
15 }
16 }
17 }
18 return count == rooms.size();
19 }
20}1class Solution {
2public:
3 bool canVisitAllRooms(vector<vector<int>>& rooms) {
4 vector<bool> seen(rooms.size(), false);
5 seen[0] = true;
6 vector<int> stack = {0};
7 int count = 1;
8 while (!stack.empty()) {
9 int room = stack.back(); stack.pop_back();
10 for (int key : rooms[room]) {
11 if (!seen[key]) {
12 seen[key] = true;
13 count++;
14 stack.push_back(key);
15 }
16 }
17 }
18 return count == (int)rooms.size();
19 }
20};Time and space complexity
O(n + k)
Each room is popped at most once, and each of the k keys is looked at once when its room is searched.
O(n)
The seen set and the stack each hold at most n rooms.
Other approaches
BFS with a queue (time O(n + k), space O(n))
Use a queue instead of a stack. Rooms are opened in order of how many keys away they are from room 0, but the set of reachable rooms and the answer are the same.
Recursive DFS (time O(n + k), space O(n))
Call visit(room), which marks the room and recurses on each unseen key. It is shorter, but a chain of 1000 rooms recurses 1000 deep, which reaches Python's default recursion limit.
Union-Find (time Not applicable, space Not applicable)
Joining room i with every key's room does not work, because keys are one-way: a key to j in room i does not let you get from j back to i. Reachability on a directed graph needs a search.
Common mistakes
- Marking a room as seen only when it is popped. The same room can then be pushed many times, once for every copy of its key.
- Treating keys as undirected edges. A key leads one way only.
- Forgetting that room 0 is already open. It must start in the seen set, or a key to room 0 would count it twice.
- Returning true as soon as the stack empties, without checking that the number of seen rooms equals n.
Frequently asked questions
Does the order rooms are visited in matter?
No. Any room you can reach stays reachable, and keys are never used up, so DFS, BFS or any other order unlocks the same set of rooms.
What if a room holds its own key?
It is just a self-loop and changes nothing. You cannot enter the room to pick that key up unless another key opened it first.
Why compare counts at the end instead of checking each room?
Every seen room is distinct, so the size of the seen set equals the number of rooms you can enter. If it equals n, every room was reached.
How is this different from counting connected components?
Components ignore direction, and here direction matters. This problem asks a single-source reachability question on a directed graph.