There are N
rooms and you start in room 0
. Each room has a distinct number in 0, 1, 2, ..., N-1
, and each room may have some keys to access the other rooms.
Formally, each room i
has a list of keys rooms[i]
, and each key rooms[i][j]
is an integer in [0, 1, ..., N-1]
where N = rooms.length
. A key rooms[i][j] = v
allows you to enter room v
directly.
Initially, all the rooms start locked except for room 0
.
You can walk back and forth between rooms freely.
Return true
if and only if you can enter every room.
Input: [[1], [2], [3], []]
Output: true
Explanation:
We start in room 0, and pick up key 1.
We then go to room 1, and pick up key 2.
We then go to room 2, and pick up key 3.
We then go to room 3.
Since we were able to go to every room, we return true.
Input: [[1,3], [3,0,1], [2], [0]]
Output: false
Explanation: We can't enter the room with number 2.
1 <= rooms.length <= 1000
0 <= rooms[i].length <= 1000
1 <= sum(rooms[i].length) <= 3000
0 <= rooms[i][j] < rooms.length
rooms[i]
are unique.[0, N-1]
.We’ll use a Breadth-First Search (BFS) or Depth-First Search (DFS) approach to explore the rooms starting from room 0
. The goal is to see if we can visit all the rooms by collecting and using keys found in each room.
0
to the stack/queue.true
. Otherwise, return false
.collections.deque
(for queue).def canVisitAllRooms(rooms):
N = len(rooms)
visited = set()
stack = [0] # start with room 0
while stack:
current_room = stack.pop()
if current_room not in visited:
visited.add(current_room)
for key in rooms[current_room]:
if key not in visited:
stack.append(key)
return len(visited) == N
# Example usage:
print(canVisitAllRooms([[1], [2], [3], []])) # Output: True
print(canVisitAllRooms([[1,3], [3,0,1], [2], [0]])) # Output: False
The time complexity of the algorithm is O(N + E), where:
We visit each room at most once and explore each key at most once.
The space complexity is also O(N + E), which includes the space for the visited
set and the stack.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?