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 the 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

Example 1 — Linear Chain
$ Input: rooms = [[1],[2],[3],[]]
Output: true
💡 Note: Start at room 0 → get key 1 → visit room 1 → get key 2 → visit room 2 → get key 3 → visit room 3. All rooms visited.
Example 2 — Disconnected Rooms
$ Input: rooms = [[1,3],[3,0,1],[2],[0]]
Output: false
💡 Note: From room 0, we can reach rooms 1 and 3. From room 1, we can't reach room 2 because we don't have key 2. Room 2 remains unreachable.
Example 3 — Single Room
$ Input: rooms = [[]]
Output: true
💡 Note: Only one room exists (room 0) and we start there, so all rooms are visited.

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

Visualization

Tap to expand
Keys and Rooms Problem OverviewRoom 0Keys: [1]✓ UnlockedRoom 1Keys: [2]🔒 LockedRoom 2Keys: [3]🔒 LockedRoom 3Keys: []🔒 LockedGraph Traversal Problem• Start at room 0 (always unlocked)• Collect keys from current room• Use keys to unlock and visit other rooms• Goal: Can we reach ALL rooms?Solution: DFS/BFS from room 0Input: rooms = [[1],[2],[3],[]] → Output: true
Understanding the Visualization
1
Input
Array of rooms, each containing keys to other rooms
2
Process
Start from room 0, collect keys, visit accessible rooms
3
Output
Return true if all rooms can be visited
Key Takeaway
🎯 Key Insight: This is a graph connectivity problem - use DFS or BFS to check if all nodes are reachable from the starting node
Asked in
Amazon 15 Microsoft 12 Google 8 Facebook 6
125.0K Views
Medium Frequency
~15 min Avg. Time
2.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen