Keys and Rooms in Python

The Keys and Rooms problem is a graph traversal challenge where we need to determine if all rooms can be visited starting from room 0. Each room contains keys to other rooms, and we need to check if we can reach every room using available keys.

Problem Understanding

Given N rooms numbered 0 to N-1, we start in room 0. Each room i contains a list of keys rooms[i], where each key opens a specific room. We need to return True if we can visit all rooms, False otherwise.

Key constraints ?

  • Initially, all rooms are locked except room 0
  • We can move freely between unlocked rooms
  • A key rooms[i][j] = v opens room number v

Algorithm Approach

We'll use a Breadth-First Search (BFS) approach with a queue to track rooms to visit and a visited array to mark accessible rooms.

Steps ?

  1. Initialize an empty queue and a visited array
  2. Start from room 0, mark it as visited
  3. Add all keys from current room to the queue
  4. Process each room in the queue until empty
  5. Return True if all rooms are visited

Implementation

class Solution:
    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:
            current_room = queue.pop(0)
            visited[current_room] = True
            queue = self.add_rooms(rooms, current_room, queue, visited)
        
        return all(visited)
    
    def add_rooms(self, rooms, index, queue, visited):
        for key in rooms[index]:
            if not visited[key]:
                queue.append(key)
        return queue

# Test the solution
solution = Solution()
rooms = [[1], [2], [3], []]
result = solution.canVisitAllRooms(rooms)
print(f"Can visit all rooms: {result}")
Can visit all rooms: True

Example Walkthrough

For input [[1], [2], [3], []] ?

# Step-by-step execution
rooms = [[1], [2], [3], []]

# Start: Room 0 (unlocked), has key [1]
# Queue: [1], Visited: [True, False, False, False]

# Process Room 1: has key [2]  
# Queue: [2], Visited: [True, True, False, False]

# Process Room 2: has key [3]
# Queue: [3], Visited: [True, True, True, False]

# Process Room 3: has no keys []
# Queue: [], Visited: [True, True, True, True]

# All rooms visited: True
print("All rooms can be visited!")
All rooms can be visited!

Alternative Example

Let's test with a case where not all rooms are accessible ?

solution = Solution()

# Room 0 has key [1], Room 1 has no keys, Room 2 is unreachable
rooms_impossible = [[1], [], [0]]
result = solution.canVisitAllRooms(rooms_impossible)
print(f"Can visit all rooms: {result}")

# Room 0 has keys [1,3], creating multiple paths
rooms_complex = [[1,3], [3,0,1], [2], [1]]
result2 = solution.canVisitAllRooms(rooms_complex)
print(f"Complex case result: {result2}")
Can visit all rooms: False
Complex case result: True

Time and Space Complexity

Time Complexity: O(N + K), where N is the number of rooms and K is the total number of keys across all rooms.

Space Complexity: O(N) for the visited array and queue storage.

Conclusion

The Keys and Rooms problem is solved using BFS traversal to explore all accessible rooms. We maintain a visited array to track reachable rooms and return True only if all rooms can be visited starting from room 0.

Updated on: 2026-03-25T08:11:53+05:30

602 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements