Suppose we have N rooms and we start in room 0. In each room there exists a distinct number in 0, 1, 2, ..., N-1, and each room may have some keys to access the next room. So in other words, 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 = number of rooms. A key rooms[i][j] = v, this opens the room with number v So if the input is [, , , ]. then output will be true. There are few more points that we should keep in mind −
So we will start from room 0 and pick up the key 1, then go to room 1, take key for 2, the form room 2, take key for 3, after visiting 3, if all rooms are visited, then return true.
To solve this, we will follow these steps −
Let us see the following implementation to get a better understanding −
class Solution(object): def canVisitAllRooms(self, rooms): queue =  visited = [False for i in rooms] queue = self.add_rooms(rooms,0,queue,visited) visited = True while len(queue)>0: queue = self.add_rooms(rooms,queue,queue,visited) visited[queue] = True queue.pop(0) return all(visited) def add_rooms(self, rooms,index,queue,visited): for i in rooms[index]: if not visited[i]: queue.append(i) return queue ob1 = Solution() print(ob1.canVisitAllRooms([,,,]))