Trains the technique from
LeetCode 841Keys and RoomsThis is an original problem, written from a brief that listed the technique, the difficulty, the topics, the function shape and the input bounds — none of that problem's wording, examples, hints or editorials. The link is there so you can map your practice onto the standard set.
Same function shape, different story and different numbers.
A depot has n numbered lockers, 0 through n - 1. Every locker is bolted shut except locker 0, which the night clerk leaves open.
Inside each locker hangs a ring of keys. lockers[i] lists the numbers of the lockers that the keys inside locker i open. A locker's ring never lists the same locker twice, though it may list a locker that is already open, and it may even list itself. Once you can open a locker you can take everything on its ring and keep going.
Starting from the open locker 0, return true if every locker in the depot can be opened, and false otherwise.
Example 1
Locker 0 is open and holds the key to locker 2. Locker 2 holds keys to lockers 1 and 3, so all four end up open.
Example 2
Locker 0 gives locker 2, locker 2 gives locker 1, and locker 1 gives locker 3.
Example 3
Lockers 0 and 1 only hold each other's keys, so lockers 2 and 3 stay shut even though their numbers do appear on rings elsewhere in the depot.
Example 4
Locker 0's ring lists itself, which changes nothing, and its other key opens locker 2, whose ring opens locker 1.
Example 5
The open locker holds no keys at all, so lockers 1 and 2 can never be opened.
The editor is preloaded with this. It matches the parent problem's shape, so a solution that works here transfers to a judge unchanged.
def can_open_all_lockers(lockers: list[list[int]]) -> bool:public boolean canOpenAllLockers(List<List<Integer>> lockers)See the step-by-step animation, the intuition, and clean code in every language — free, no credit card.