Imagine you're exploring a mysterious mansion with n rooms labeled from 0 to n-1. All rooms are locked except for room 0, which serves as your starting point. Your mission is to visit every single room in the mansion.

Here's the catch: you can only enter a locked room if you have its specific key! Fortunately, each room you visit might contain a set of keys that unlock other rooms. Each key has a number indicating which room it opens, and you can collect all the keys you find.

Input: An array rooms where rooms[i] contains all the keys you'll find in room i.

Output: Return true if you can visit all rooms, false otherwise.

Example: If rooms = [[1],[2],[3],[]], you start in room 0, find key 1, use it to enter room 1, find key 2, enter room 2, find key 3, enter room 3. All rooms visited โ†’ return true!

Input & Output

example_1.py โ€” Basic Connected Graph
$ Input: rooms = [[1],[2],[3],[]]
โ€บ Output: true
๐Ÿ’ก Note: Start in room 0, get key 1 โ†’ visit room 1, get key 2 โ†’ visit room 2, get key 3 โ†’ visit room 3. All 4 rooms visited successfully.
example_2.py โ€” Disconnected Graph
$ Input: rooms = [[1,3],[3,0,1],[2],[0,1]]
โ€บ Output: false
๐Ÿ’ก Note: Start in room 0, can visit rooms 1 and 3, but room 2 is unreachable because no room we can access contains key 2.
example_3.py โ€” Single Room
$ Input: rooms = [[]]
โ€บ Output: true
๐Ÿ’ก Note: Only one room (room 0) exists and we start there, so all rooms are visited by default.

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
0123key 1key 3key 2STARTDFS Traversal OrderRoom 0 โ†’ Room 1 โ†’ Room 2Room 0 โ†’ Room 3
Understanding the Visualization
1
Model as Graph
Each room is a node, each key creates an edge to another room
2
Start DFS from Room 0
Begin traversal from the unlocked starting room
3
Follow Key Edges
For each key found, traverse to that room if not visited
4
Check Connectivity
All rooms visited means the graph is fully connected from room 0
Key Takeaway
๐ŸŽฏ Key Insight: This is a graph connectivity problem! Use DFS/BFS to explore all reachable rooms from the starting point.
Asked in
Amazon 45 Google 38 Microsoft 32 Meta 28
68.5K Views
Medium Frequency
~15 min Avg. Time
2.5K 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