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 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.
Examples
Example 1:
|
|
Example 2:
|
|
Solution
Method 1 – BFS Traversal
Intuition
We treat each room as a node and each key as an edge to another node. Starting from room 0, we use BFS to visit all rooms we can reach using the keys found. If all rooms are visited, return true; otherwise, false.
Approach
- Initialize a queue with room 0 and a visited set.
- While the queue is not empty:
- Pop a room from the queue.
- For each key in the room, if the room is not visited, add it to the queue and mark as visited.
- After traversal, check if all rooms are visited.
Code
Java
|
|
Complexity
- ⏰ Time complexity:
O(n + m)
, wheren
is the number of rooms andm
is the total number of keys. - 🧺 Space complexity:
O(n)
, for the visited array and queue.
Method 2 – DFS Traversal
Intuition
We can also use DFS to visit all rooms starting from room 0, recursively visiting rooms using the keys found. If all rooms are visited, return true; otherwise, false.
Approach
- Initialize a visited array.
- Define a recursive DFS function to visit rooms.
- Start DFS from room 0.
- After traversal, check if all rooms are visited.
Code
Java
|
|
Complexity
- ⏰ Time complexity:
O(n + m)
, wheren
is the number of rooms andm
is the total number of keys. - 🧺 Space complexity:
O(n)
, for the visited array and recursion stack.