Online store~12 min2s · 256 MBtarget O(n + k) time, O(n) spaceclassic twin: lc-841dfs
An online store keeps returned goods in a building of n rooms, numbered 0 to n - 1. Every room is locked except room 0. Each room holds key tags, and each tag opens the door of one room.
Your team lead says: "A new picker starts in room 0 with no other key. Tell me how many rooms they can open, using only the tags they find along the way."
You work on the building's access app, which prints that number before a shift.
Write rooms_unlocked(keys).
keys[i] lists the rooms whose doors the key tags in room i open. The number of rooms is len(keys).0 is open at the start. A picker may enter any open room and take all of its key tags.0 included.A tag may open the room that holds it, or a room that is already open, and the same tag may appear more than once.
Input: keys = [[1, 3], [3, 0, 1], [2], [0]]
Output: 3The search keeps a stack of open rooms it has not yet searched. A room is marked open when its door is opened.
| Taken from the stack | Keys found there | Newly opened | Stack after (top on the right) |
|---|---|---|---|
| room 0 | 1, 3 | 1, 3 | 1, 3 |
| room 3 | 0 | none | 1 |
| room 1 | 3, 0, 1 | none | empty |
Rooms 0, 1 and 3 open. Room 2 holds only the tag for its own door, and nobody outside holds a tag for it.
Input: keys = [[1], [2], [3], []]
Output: 4Each room holds the tag for the next one, so the whole building opens.
Input: keys = [[]]
Output: 1One room, already open.
1 ≤ len(keys) ≤ 100,000keys[i] is a room number from 0 to len(keys) - 1.There can be 100,000 rooms and 200,000 tags. A walk that opens each room once and tries each tag once takes about 300,000 steps. Passing over every room again and again, until a pass opens nothing, can take 100,000 passes, which is about 10 billion steps.