Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
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
uas seen - for each
vinrooms[u], do- if
vis not seen, then- insert
vat the end of ready
- insert
- if
-
- 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
readystack - 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 returnTrue
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.
