Problem statement

https://binarysearch.com/problems/Unlock-Rooms/

Solution

Equal to Leetcode 0841. Keys and Rooms.

Complexity

It is O(N + E) for time and O(N) for space.

Code

class Solution:
    def solve(self, rooms):
        visited = set([0])
        
        def dfs(room):
            for neib in rooms[room]:
                if neib not in visited:
                    visited.add(neib)
                    dfs(neib)
                    
        dfs(0)
        return len(visited) == len(rooms)