LeetCode in Python 841. Keys and Rooms

Example 1:

Input: [[1],[2],[3],[]]
Output: true
Explanation:  
We start in room 0, and pick up key 1.
We then go to room 1, and pick up key 2.
We then go to room 2, and pick up key 3.
We then go to room 3.  Since we were able to go to every room, we return true.

Example 2:

Input: [[1,3],[3,0,1],[2],[0]]
Output: false
Explanation: We can't enter the room with number 2.

Note:

  1. 1 <= rooms.length <= 1000
  2. 0 <= rooms[i].length <= 1000
  3. The number of keys in all rooms combined is at most 3000.

典型的DFS,跟之前的一个手机键盘拨号很像

BFS Solution:

class Solution(object):  
    def canVisitAllRooms(self, rooms):
        """
        :type rooms: List[List[int]]
        :rtype: bool
        """
        visited = [0 for i in range(len(rooms))]
        visited[0] = 1
        def bfs(hasKey):
            for index in hasKey:
                newRooms = []
                for room in rooms[index]:
                    if not visited[room]:
                        newRooms.append(room)
                        visited[room] = 1
                bfs(newRooms)
        
        bfs([0])
        for i in visited:
            if not i:
                return False
        return True     

  

 更短的DFS解法,加上一个path代表遍历的路径(classic dfs),最后对比路径的长度与房间的总数:

class Solution(object):  
    def canVisitAllRooms(self, rooms):
        """
        :type rooms: List[List[int]]
        :rtype: bool
        """
        return len(self.dfs(rooms, [])) == len(rooms)
    
    def dfs(self, rooms, path, source=0):
        path += [source]
        for i in rooms[source]:
            if i not in path:
                self.dfs(rooms, path, i)
        return path
        

  

 更短的BFS:

class Solution(object):  
    def canVisitAllRooms(self, rooms):
        """
        :type rooms: List[List[int]]
        :rtype: bool
        """
        q, path = [0], [0]
        while q:
            size = len(q)
            for i in range(size):
                index = q.pop(0)
                for v in rooms[index]:
                    if v not in path:
                        q.append(v)
                        path.append(v)
        return len(path) == len(rooms)

  

posted @ 2019-07-10 11:32  bossman  阅读(159)  评论(0编辑  收藏  举报