Keys and Rooms LeetCode solution in Python

1
class Solution:
2
def canVisitAllRooms(self, rooms: List[List[int]]) -> bool:
3
# Create a set of for rooms visited
4
visited_rooms = set()
5

6
# Create a queue to do a breadth first search visiting rooms
7
# Append the first room, 0, to the queue to begin the search
8
queue = collections.deque()
9
queue.append(0)
10

11
# Perform the breadth first search with the queue
12
while queue:
13
for _ in range(0, len(queue)):
14
# Search the room
15
room_number = queue.popleft()
16

17
# If we haven't visited the room, get the keys from the room
18
if room_number not in visited_rooms:
19

20
# Collect the keys from the room
21
found_keys = rooms[room_number]
22

23
# Add the keys to the queue so they can be tested
24
for key in found_keys:
25
queue.append(key)
26

27
# Add the current room to the visited set
28
visited_rooms.add(room_number)
29

30
# If we visited all of the rooms, then the number of visited rooms should be
31
# equal to the number of total rooms
32
if len(visited_rooms) == len(rooms):
33
return True
34

35
return False

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0