代码如下:

import collections
class Solution:
    def canVisitAllRooms(self, rooms):
        to_check = collections.deque([0])
        keys = collections.deque([0])
        while to_check:
            key = to_check.popleft()
            for i in range(len(rooms[key])):
                if rooms[key][i] not in keys:
                    to_check.append(rooms[key][i])
                    keys.append(rooms[key][i])
        if len(keys) == len(rooms):
            return True
        else:
            return False
rooms = [[1,3],[3,0,1],[2],[0]]
print(Solution().canVisitAllRooms(rooms))

运行结果如下,可以看到

841. Keys and Rooms刷题笔记_List


看了一下参考答案 它把我这边的已经访问过的keys做成了列表,这样子可以加快访问速度,不过会牺牲一些空间

它主要做了两个优化:

  1. 用all来判断数组是否全为1
  2. 迭代的元素不用下标,直接对列表进行迭代
    pycharm代码
class Solution:
    def canVisitAllRooms(self, rooms: List[List[int]]) -> bool:
        to_check = collections.deque([0])
        seen = [False]*len(rooms)
        seen[0] = True
        while to_check:
            key = to_check.popleft()
            for inside_key in rooms[key]:
                if seen[inside_key]:
                    continue
                seen[inside_key] = True
                to_check.append(inside_key)
        return all(seen)

运行结果:

841. Keys and Rooms刷题笔记_List_02