Python coding

Unlock every room

There are n rooms numbered 0 to n - 1, and only room 0 starts unlocked. Inside room i you find the keys listed in keys[i]; each key is the number of the room it opens. Keys never wear out and you can carry as many as you like. Return True if you can get into every room, otherwise False.

keys has n ≥ 1 entries. A room may hold no keys, the same key twice, or its own key.

Besides the tests, one large input (2,500 rooms) with a ~100 ms limit (scaled to your device's speed): brute force won't pass.

  • can_open_all([[1],[2],[3],[]]) → true
  • can_open_all([[2],[],[1]]) → true
  • can_open_all([[1],[0],[3],[2]]) → false
Ctrl/⌘ + Enter runs · Tab indents
Hint 1

Think of each room as a node and each key as a one-way edge to the room it opens. The question is whether every node can be reached from room 0.

Hint 2

Run a DFS from room 0 with a stack and a visited set, marking a room when you push it. At the end, compare how many rooms you visited with n.

Solution and why it works
pythonO(n + k), k = total keys · O(n)
def can_open_all(keys: list[list[int]]) -> bool:
    opened, stack = {0}, [0]
    while stack:
        for room in keys[stack.pop()]:
            if room not in opened:
                opened.add(room)                 # mark on push: each room is entered once
                stack.append(room)
    return len(opened) == len(keys)

Keys are one-way edges, so the question is whether every room is reachable from room 0, and one DFS (or BFS) answers it. Marking a room when it is pushed means each room is entered once and each key is read once: O(n + k). The order you open rooms in doesn't matter, because keys never run out. The trap is sweeping the rooms in number order until a pass opens nothing new: when keys point backwards, each pass opens one room, O(n²).