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 - DFS Approach INPUT Room Graph Structure 0 START 1 2 3 key 1 key 2 key 3 Input Array: [1] room 0 [2] room 1 [3] room 2 [] room 3 n = 4 rooms ALGORITHM STEPS 1 Initialize visited = {0}, stack = [0] 2 DFS from Room 0 Pop 0, find key 1 3 Continue DFS Visit 1-->2-->3 4 Check Result visited.size == n? DFS Traversal Order: 0 --> 1 --> 2 --> 3 visited = {0, 1, 2, 3} All 4 rooms visited! FINAL RESULT All Rooms Visited: 0 OK 1 OK 2 OK 3 OK Output: true visited.size (4) == n (4) All rooms accessible! Key Insight: This problem is a graph traversal where rooms are nodes and keys represent directed edges. DFS starts from room 0, collects keys, and visits new rooms. If visited count equals n, return true. Time: O(n + k) where k = total keys | Space: O(n) for visited set and recursion stack. TutorialsPoint - Keys and Rooms | Depth-First Search (DFS)
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