LeetCode 841. Keys and Rooms

Post by ailswan June. 28, 2024

841. Keys and Rooms

Problem Statement

link: LeetCode.cn LeetCode There are n rooms labeled from 0 to n - 1 and all the rooms are locked except for room 0. Your goal is to visit all the rooms. However, you cannot enter a locked room without having its key.

When you visit a room, you may find a set of distinct keys in it. Each key has a number on it, denoting which room it unlocks, and you can take all of them with you to unlock the other rooms.

Given an array rooms where rooms[i] is the set of keys that you can obtain if you visited room i, return true if you can visit all the rooms, or false otherwise.

Example:

Input: rooms = [[1],[2],[3],[]] Output: true

Input: rooms = [[1,3],[3,0,1],[2],[0]] Output: false

Solution Approach

Algorithm

Implement

    class Solution: def canVisitAllRooms(self, rooms: List[List[int]]) -> bool:
    # map {room: keys}
    # enter = [] track the room can enter
    # visited  set of room number
    # if enter is empty: check len(visited) == rooms
    enter = deque([0])
    mapR = defaultdict(list)
    for r in range(len(rooms)):
        mapR[r] = rooms[r]
    visited = {0}
    while enter:
        cur = enter.popleft()
        keys = mapR[cur]
        for k in keys:
            if not k in visited:
                enter.append(k)
                visited.add(k)
    return len(visited) == len(rooms)