Keys and Rooms
Difficulty: Medium · Pattern: Graphs (BFS / DFS) · LeetCode #841
There are n rooms. Only room 0 is unlocked at first. rooms[i] lists the keys found in room i, and each key opens the room with that number. Return true if you can visit every room.
Examples
text
[[1],[2],[3],[]] → true
[[1,3],[3,0,1],[2],[0]] → false (room 2's only key is in room 2)Hints
- Rooms are nodes and keys are directed edges. The question is whether everything is reachable from node 0.
Approach
DFS/BFS from room 0 with a seen set, then compare len(seen) with n. This is the most basic graph question there is: reachability.
Complexity
Time: O(rooms + keys). Space: O(rooms).
Python solution
def canVisitAllRooms(rooms):
seen, stack = {0}, [0]
while stack:
for k in rooms[stack.pop()]:
if k not in seen:
seen.add(k)
stack.append(k)
return len(seen) == len(rooms)JavaScript solution
function canVisitAllRooms(rooms) {
const seen = new Set([0]), stack = [0];
while (stack.length) for (const k of rooms[stack.pop()]) if (!seen.has(k)) { seen.add(k); stack.push(k); }
return seen.size === rooms.length;
}