Keys and Rooms
LeetCode 841 · Medium · solution, intuition & step-by-step walkthrough
BFS from room 0 over key edges.
This is how I solved Keys and Rooms (LeetCode 841), a medium problem from the Graph Fundamentals / DFS pattern. Below: the intuition, the approach step by step, my accepted Python code, animated test cases and a line-by-line debugger.
Intuition
Rooms are nodes and keys are edges. Starting from room 0, BFS through every room you can unlock; you succeed if every room gets visited.
Approach
- 1
Mark room 0 visited and enqueue it.
- 2
For each key in a room, visit unvisited rooms.
- 3
Return all(visited).
How I solved it
BFS reachabilityPythonO(N+K) time
class Solution:
def canVisitAllRooms(self, rooms: List[List[int]]) -> bool:
"""
0 - [1]
1 - [2]
2 - [3]
3 - []
with the key at room 0 we can visit room 1
0 -> 1 [adj list]
0 has keys- 1,3 so from 0 we can visit 1,3
"""
n = len(rooms)
visited = [False]*n
visited[0]=True
q = deque([0])
while q:
node = q.popleft()
for adj_node in rooms[node]:
if visited[adj_node]==False:
visited[adj_node]=True
q.append(adj_node)
return all(visited)Keys and Rooms — FAQ
What is the intuition behind Keys and Rooms?
Rooms are nodes and keys are edges. Starting from room 0, BFS through every room you can unlock; you succeed if every room gets visited.
How do you solve Keys and Rooms (LeetCode 841)?
1. Mark room 0 visited and enqueue it. 2. For each key in a room, visit unvisited rooms. 3. Return all(visited).
What is the time and space complexity of Keys and Rooms?
Time: O(N + K). Space: O(N). (Accepted approach: BFS reachability.)
What are common mistakes in Keys and Rooms?
A key to an already-visited room is ignored.