Key and room | Python


841. Keys and rooms

Source: leetcode


There are n rooms. You were in room 0 at the beginning. Each room has a different number: 0, 1, 2,…, n-1, and there may be some keys in the room that will allow you to enter the next room.

Formally, there is a key list rooms [i] for each room I. each key room Si is represented by an integer in [0,1,…, n-1], where n= rooms.length 。 Room number V can be opened by the key roomsi = v.

Initially, all the rooms except room 0 were locked.

You are free to move between rooms.

Return true if you can enter each room, otherwise return false.

Example 1:

Input: [[1], [2], [3], []]
Output: true
We'll start in room 0 and get the key 1.
Then we go to room 1 and get the key 2.
Then we go to room 2 and get the key 3.
Finally, we went to room 3.
Since we can enter each room, we return true.

Example 2:

Input: [[1,3], [3,0,1], [2], [0]]
Output: false
Explanation: we can't get into room 2.


  • 1 <= rooms.length <= 1000
  • 0 <= rooms[i].length <= 1000
  • The total number of keys in all rooms does not exceed 3000.

Thinking of problem solving

Idea: DFS, BFS

First look at the title, the title requirements from room 0, ask whether you can enter each room? Among them, room 0 was opened at the beginning, while all the other rooms were locked. In theory, every room has a key (but according toTip 2May not have) keys corresponding to other rooms (including the current room,Room 1 in example 2)。

Here, we can find that it is like a directed graph, and the key determines the directed edges of two points. Starting from a certain point, can we reach all the points?

The array given in the title isAdjacency listThen we can consider using the idea of depth first search (DFS) and breadth first search (BFS) to traverse the whole graph to see if we can search all the points. Here we use set to record the visited rooms.

The specific code implementation is as follows.


class Solution:
    def canVisitAllRooms(self, rooms: List[List[int]]) -> bool:
        #Use collective storage to access rooms to ensure that they are not repeated
        #Then compare the number of rooms directly to get whether to visit all rooms
        visited = set()

        def dfs(cur_room):
            #Add tag first
            #Get the key here
            next_keys = rooms[cur_room]
            #According to the key to access other rooms, the access to skip
            for i in range(len(next_keys)):
                next_room = next_keys[i]
                if next_room not in visited:

        return len(visited) == len(rooms)


class Solution:
    def canVisitAllRooms(self, rooms: List[List[int]]) -> bool:
        #The collection stores the accessed rooms to ensure that they are not repeated
        visited = set()

        from collections import deque
        queue = deque()
        #Also from room 0
        while queue:
            #Get the room number in the queue first
            room_num = queue.popleft()
            #Go to the corresponding room to find the key
            next_keys = rooms[room_num]

            for i in range(len(next_keys)):
                #Go to the corresponding room with the key
                next_room_num = next_keys[i]
                #Judge whether to visit or not. Skip if you have
                if next_room_num not in visited:
        #Compare visited and rooms
        return len(visited) == len(rooms)

Welcome to our attention

The official account [book collection]

Recommended Today

SDS of redis data structure

SDS(simple dynamic string), simple dynamic string. S and it’s called hacking string. Where hack is stored is the length of the string and the remaining space in SDS. The implementation of SDS insds.cIn the middle. C language string uses a character array of length N + 1 to represent the string of length N, and […]