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)