Skip to content
Veltoryx Technologies
FreeProblem 121● MediumLeetCode #841 ↗3 min readUpdated 30 October 2026

Keys and Rooms

Determine if you can visit every room starting from room 0 using graph reachability DFS.

01The problem

There are n rooms labeled from 0 to n - 1 and all the rooms are locked except for room 0. Your goal is to visit all the rooms. However, you cannot enter a locked room without having its key.

When you visit a room, you may find a set of distinct keys in it. Each key has a number on it, denoting which room it unlocks, and you can take all of them with you to unlock other rooms.

Given an array rooms where rooms[i] is the set of keys that you can obtain if you visited room i, return true if you can visit all the rooms, or false otherwise.

InputOutputWhy
rooms = [[1],[2],[3],[]]trueRoom 0 unlocks 1, 1 unlocks 2, 2 unlocks 3. All 4 visited.
rooms = [[1,3],[3,0,1],[2],[0]]falseRoom 2 cannot be unlocked (key 2 is inside room 2).

Constraints

  • n == rooms.length
  • 2 <= n <= 1000
  • 0 <= rooms[i].length <= 1000
  • 1 <= sum(rooms[i].length) <= 3000
  • 0 <= rooms[i][j] < n
  • All the values of rooms[i] are unique.

02How to spot it

  • "Can all rooms be visited starting from 0": Single-source graph reachability!
  • DFS / BFS with visited array: The rooms array is already an adjacency list! Start at node 0, traverse all reachable nodes, and check if visitedCount == n.

03Pseudocode

text
open[0] = true ; stack = [0]
while stack:
  room = pop
  for key in rooms[room]:
    if not open[key]:
      open[key] = true ; push key
return opened == n

04Watch it work

Visualizer · step through the algorithmrooms = [[1],[2],[3],[]]

open rooms

true0
false1
false2
false3

opened count

1/4

Start at Room 0: mark open[0] = true. DFS through keys to see if all rooms can be unlocked.

Pseudocode

  1. open[0] = true ; stack = [0]
  2. while stack:
  3. room = pop
  4. for key in rooms[room]:
  5. if not open[key]:
  6. open[key] = true ; push key
  7. return opened == n

Variables

open
true,false,false,false
opened
1
step 1 / 5

05Step-by-step dry run

We trace rooms = [[1],[2],[3],[]]:

Popped roomKeys obtainedNewly unlocked roomsopened count
0[1]Room 1 unlocked2
1[2]Room 2 unlocked3
2[3]Room 3 unlocked4
3[]None4 == n -> true!

Output: true.

06Java solution

java
import java.util.*;

public class Solution {
    public static boolean canVisitAllRooms(List<List<Integer>> rooms) {
        int n = rooms.size();
        boolean[] open = new boolean[n];
        Deque<Integer> stack = new ArrayDeque<>();

        open[0] = true;
        stack.push(0);
        int opened = 1;

        while (!stack.isEmpty()) {
            int room = stack.pop();
            for (int key : rooms.get(room)) {
                if (!open[key]) {
                    open[key] = true;
                    opened++;
                    stack.push(key);
                }
            }
        }
        return opened == n;
    }

    public static void main(String[] args) {
        List<List<Integer>> rooms = Arrays.asList(
            Collections.singletonList(1),
            Collections.singletonList(2),
            Collections.singletonList(3),
            Collections.emptyList()
        );
        System.out.println(canVisitAllRooms(rooms));
    }
}
Expected output
true

07Why it works

rooms directly represents a directed graph adjacency list where keys are directed edges. Launching DFS from node 0 visits every vertex in the connected component reachable from 0. Comparing opened == n verifies full reachability.

08Time and space

  • Time complexity: O(V + E) where V = n and E = sum(rooms[i].length). Each room and key is examined once.
  • Space complexity: O(n) to store the open boolean array and stack.

09Edge cases

  • Disconnected graph: Returns false because some nodes remain unvisited.
  • Cycles in keys (e.g. room 1 has key to 0): Handled safely by open check; loops are prevented.

10In the interview

  • Opening line: "The rooms array is already an adjacency list. I will start DFS from room 0, marking visited rooms and counting total rooms reached. If the count equals n, return true."

11Quiz

What does rooms[i] represent in graph terminology?

  • (Recommended) The outgoing directed edges from vertex i
  • The incoming edges to vertex i
  • The weight of vertex i
  • The number of vertices in the graph

Answer: The outgoing directed edges from vertex i. Each key inside room i lets you visit that destination room.

12Solve it yourself

Open LeetCode #841 and submit the DFS solution.