-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path87.Keys_and_Rooms.py
22 lines (19 loc) · 1.25 KB
/
87.Keys_and_Rooms.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# 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 next room.
# 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 opens the room with number v.
# 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.
class Solution:
def canVisitAllRooms(self, rooms: list) -> bool:
seen = [False] * len(rooms)
seen[0] = True
stack = [0]
#At the beginning, we have a todo list "stack" of keys to use.
#'seen' represents at some point we have entered this room.
while stack: #While we have keys...
node = stack.pop() # get the next key 'node'
for nei in rooms[node]: # For every key in room # 'node'...
if not seen[nei]: # ... that hasn't been used yet
seen[nei] = True # mark that we've entered the room
stack.append(nei) # add the key to the todo list
return all(seen) # Return true iff we've visited every room