Keys and Rooms in Python

PythonServer Side ProgrammingProgramming

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 [[1], [2], [3], []]. then output will be true. There are few more points that we should keep in mind −

  • Initially, all the rooms start locked (except for room 0).
  • We can walk back and forth between rooms freely.
  • We should return true if and only if we can enter every room.

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 −

  • make one empty queue, and make a visited array for all rooms and set as false
  • queue := addRooms(rooms, 0, queue, visited)
  • visited[0] :=Ture
  • while queue has some element
    • queue := addRooms(rooms, queue[0], queue, visited)
    • mark visited[queue[0]] as true,
    • delete the element from queue
  • return true, when all elements are true in the visited array
  • The addRoom() will take rooms, index, queue and visited array, this will be like
  • for i in rooms[index] array
    • if i is not visited, then insert i into queue
  • return queue

Example(Python)

Let us see the following implementation to get a better understanding −

 Live Demo

class Solution(object):
   def canVisitAllRooms(self, rooms):
      queue = []
      visited = [False for i in rooms]
      queue = self.add_rooms(rooms,0,queue,visited)
      visited[0] = True
      while len(queue)>0:
         queue = self.add_rooms(rooms,queue[0],queue,visited)
         visited[queue[0]] = 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([[1],[2],[3],[]]))

Input

[[1],[2],[3],[]]

Output

true
raja
Published on 27-Feb-2020 11:10:53
Advertisements