Tensorum
LeetCode 841 · Graph Fundamentals / DFS

Keys and Rooms

LeetCode 841 · Medium · solution, intuition & step-by-step walkthrough

BFS from room 0 over key edges.

MediumDepth-First SearchBreadth-First SearchGraph Theory
0 msruntime · beats 100%
19.9 MBmemory · beats 35%
1approach
4accepted runs · last 18 Sept 2026

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. 1

    Mark room 0 visited and enqueue it.

  2. 2

    For each key in a room, visit unvisited rooms.

  3. 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)
Loading the step-through…

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.