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.
| Input | Output | Why |
|---|---|---|
rooms = [[1],[2],[3],[]] | true | Room 0 unlocks 1, 1 unlocks 2, 2 unlocks 3. All 4 visited. |
rooms = [[1,3],[3,0,1],[2],[0]] | false | Room 2 cannot be unlocked (key 2 is inside room 2). |
Constraints
n == rooms.length2 <= n <= 10000 <= rooms[i].length <= 10001 <= sum(rooms[i].length) <= 30000 <= 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
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 == n04Watch it work
open rooms
opened count
1/4
Start at Room 0: mark open[0] = true. DFS through keys to see if all rooms can be unlocked.
Pseudocode
- 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
Variables
- open
- true,false,false,false
- opened
- 1
05Step-by-step dry run
We trace rooms = [[1],[2],[3],[]]:
| Popped room | Keys obtained | Newly unlocked rooms | opened count |
|---|---|---|---|
0 | [1] | Room 1 unlocked | 2 |
1 | [2] | Room 2 unlocked | 3 |
2 | [3] | Room 3 unlocked | 4 |
3 | [] | None | 4 == n -> true! |
Output: true.
06Java solution
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));
}
}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)whereV = nandE = sum(rooms[i].length). Each room and key is examined once. - Space complexity:
O(n)to store theopenboolean array and stack.
09Edge cases
- Disconnected graph: Returns
falsebecause some nodes remain unvisited. - Cycles in keys (e.g. room 1 has key to 0): Handled safely by
opencheck; 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.