• leetcode841 Keys and Rooms


     1 """
     2 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.
     3 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.
     4 Initially, all the rooms start locked (except for room 0).
     5 You can walk back and forth between rooms freely.
     6 Return true if and only if you can enter every room.
     7 Example 1:
     8 Input: [[1],[2],[3],[]]
     9 Output: true
    10 Explanation:
    11 We start in room 0, and pick up key 1.
    12 We then go to room 1, and pick up key 2.
    13 We then go to room 2, and pick up key 3.
    14 We then go to room 3.  Since we were able to go to every room, we return true.
    15 Example 2:
    16 Input: [[1,3],[3,0,1],[2],[0]]
    17 Output: false
    18 Explanation: We can't enter the room with number 2.
    19 """
    20 """
    21 有两种方法,分别是BFS和DFS
    22 解法一:BFS
    23 用一个queue来存能到达的room
    24 用一个set来存能拿到的房间钥匙
    25 返回值为set里的钥匙数 和 房间数是否相等
    26 """
    27 class Solution1:
    28     def canVisitAllRooms(self, rooms):
    29         queue = [0]
    30         s = set()
    31         s.add(0)  #!!!bug 没有初始化开0门的钥匙
    32         while queue:
    33             keys = queue.pop()
    34             for key in rooms[keys]:
    35                 if key not in s:
    36                     s.add(key)
    37                     queue.append(key)
    38         return len(s) == len(rooms)
    39 
    40 """
    41 解法二:DFS
    42 建立一个set存钥匙,从rooms[0]开始递归
    43 将找到的key存入set里
    44 继续递归访问rooms[key]
    45 """
    46 class Solution2:
    47     def canVisitAllRooms(self, rooms):
    48         s = set()
    49         s.add(0)
    50         def enterroom(keys):
    51             for key in keys:
    52                 if key not in s:
    53                     s.add(key)
    54                     enterroom(rooms[key])
    55                 # else:
    56                 #     pass
    57             return
    58         enterroom(rooms[0])
    59         return len(s) == len(rooms)
  • 相关阅读:
    MyMacro
    CConfigXmlFile02
    “十步一杀” 干掉你的职场压力
    只有聪明人才悟到:通向成功的饥饿法则
    高层管理者应具备什么样的特点? (转)
    两个小故事,告诉你不可不知的成功密码
    中秋望月
    锦里中秋有感
    支招:如何增强创业信心,克服创业恐惧?
    创业者必看:创业得出的10条血泪经验
  • 原文地址:https://www.cnblogs.com/yawenw/p/12314985.html
Copyright © 2020-2023  润新知