841. Keys and Rooms
- Keys and Rooms python solution
题目描述
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[List[int]]) -> bool:
dfs=[0]
seen=set(dfs)
while dfs:
i=dfs.pop()
for j in rooms[i]:
if j not in seen:
dfs.append(j)
seen.add(j)
if len(seen)==len(rooms): return True
return len(seen)==len(rooms)
Reference
https://leetcode.com/problems/keys-and-rooms/discuss/133855/Straight-Forward