Program to check whether we can unlock all rooms or not in python

Suppose we have a list of lists called rooms. Each index i in rooms represents a room and rooms[i] represents different keys to open other rooms. Room 0 is open and we start there, while every other room is locked. We can move freely between opened rooms ? we need to check whether we can open every room or not.

So, if the input is like rooms = [[2, 0], [3], [1], []], then the output will be True. We start from room 0 and can go to room 2 with its key 2. From room 2 we can go to room 1. Then, take the key for room 3 and open it. So all rooms are opened.

Algorithm Steps

To solve this, we will follow these steps ?

  • n := size of rooms
  • ready := a list with single element 0
  • seen := a new set
  • while ready is not empty, do
    • u := last element of ready and delete it from ready
    • mark u as seen
    • for each v in rooms[u], do
      • if v is not seen, then
        • insert v at the end of ready
  • return true when size of seen is same as n, otherwise false

Implementation

Let us see the following implementation to get better understanding ?

class Solution:
    def solve(self, rooms):
        n = len(rooms)
        
        ready = [0]
        seen = set()
        
        while ready:
            u = ready.pop()
            seen.add(u)
            
            for v in rooms[u]:
                if v not in seen:
                    ready.append(v)
        
        return len(seen) == n

# Test the solution
ob = Solution()
rooms = [
    [2, 0],
    [3],
    [1],
    []
]
print(ob.solve(rooms))

Output

True

How It Works

The algorithm uses a depth-first search (DFS) approach ?

  • We start with room 0 in our ready stack
  • We visit each room, mark it as seen, and add all accessible rooms to our stack
  • We continue until no more rooms can be visited
  • If we've seen all rooms (len(seen) == n), we return True

Alternative Using BFS

We can also solve this using breadth-first search with a queue ?

from collections import deque

def can_visit_all_rooms(rooms):
    n = len(rooms)
    visited = set([0])
    queue = deque([0])
    
    while queue:
        room = queue.popleft()
        for key in rooms[room]:
            if key not in visited:
                visited.add(key)
                queue.append(key)
    
    return len(visited) == n

# Test the BFS solution
rooms = [[2, 0], [3], [1], []]
print(can_visit_all_rooms(rooms))

Output

True

Conclusion

This problem can be solved using either DFS or BFS traversal. The key insight is to track visited rooms and continue exploring until no new rooms can be accessed. Time complexity is O(N + K) where N is the number of rooms and K is the total number of keys.

Updated on: 2026-03-25T12:51:30+05:30

347 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements