Determine whether all rooms can be entered starting from room 0 using the keys found along the way.
Keys and Rooms
You are given a list of rooms. Each room may contain keys to other rooms. You start in room 0, and initially only room 0 is unlocked.
Whenever you enter a room, you can collect every key inside it and use those keys to unlock additional rooms. The task is to determine whether it is possible to visit every room in the building by repeatedly taking keys from rooms you have already entered.
Return true if every room can be visited, otherwise return false.
Notes
- You may enter a room only if you already have its key.
- A key can be reused any number of times.
- The order in which you explore rooms does not matter as long as all reachable rooms are eventually visited.
Input Format
rooms: a list whererooms[i]contains the keys found in roomi.- Room numbering starts at
0. - Each key is an integer referring to another room index.
Output Format
- Return a boolean value.
trueif all rooms are reachable from room0.falseotherwise.
Constraints
1 <= rooms.length- Each
rooms[i]is a list of room indices. - Room indices are valid for the given input.
- Keys may repeat across rooms.
Example 1
Input
rooms = [[1],[2],[3],[]]
Output
true
Explanation
Starting from room 0, you get key 1, then from room 1 key 2, then from room 2 key 3, so every room can be visited.
Example 2
Input
rooms = [[1,3],[3,0,1],[2],[0]]
Output
false
Explanation
Room 0 lets you enter rooms 1 and 3, but no path reaches room 2. Therefore not all rooms are visitable.
Premium problem context
Unlock deeper context for this problem
Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.