Python 0841.py
class Solution:
def canVisitAllRooms(self, rooms: List[List[int]]) -> bool:
size = len(rooms)
closed = set(range(size))
keys = [ 0 ]
while keys:
next = []
for open in keys:
if open in closed:
keys += rooms[open]
closed.discard(open)
keys = next
return not closed
Difficulty
and has an acceptance rate of about 76% (900k+ submissions).
Typical patterns to solve this problem:
- Breadth First Search
- Depth First Search
- Graph Theory
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided implementation determines whether every room in a collection can be visited starting from room 0. Each room contains a list of keys that open other rooms. The algorithm explores reachable rooms by repeatedly processing a dynamic list of keys, marking rooms as opened, and discarding them from a set that initially contains all room indices. The final result is true when the set of closed rooms becomes empty.
Key Steps
Initialization
size = len(rooms)
closed = set(range(size))
keys = [0]
The code records the total number of rooms, creates a set closed that initially holds every room index, and seeds the exploration with a list keys containing only the starting room (index 0).
Main Exploration Loop
while keys:
next = []
for open in keys:
if open in closed:
keys += rooms[open]
closed.discard(open)
keys = next
The loop continues as long as there are keys to process. Inside the loop a fresh list next is prepared for the next iteration. For each room index open in the current keys list, the algorithm checks whether the room is still marked as closed. If it is, the keys found inside that room (rooms[open]) are appended to the keys list, and the room is removed from closed. After the inner loop finishes, keys is replaced by next, which is empty in this implementation, causing the outer loop to terminate when no new rooms are discovered.
Final Result
return not closed
The function returns True when the closed set is empty, indicating that every room has been visited; otherwise it returns False.
Edge Cases Handled
When the input contains a single room, the initialization creates closed as {0} and keys as [0]. The loop processes room 0, discards it from closed, and adds any keys it may contain (which are irrelevant for a single room). After the iteration, closed becomes empty, and the function correctly returns True.
If a room contains duplicate keys, the keys += rooms[open] statement simply extends the list with those duplicates. The subsequent membership test if open in closed ensures that a room already opened will not be processed again, preventing infinite loops even when keys point back to previously visited rooms.
When some rooms are completely isolated (no incoming keys), those indices remain in the closed set because they are never added to keys. The final check not closed correctly yields False for such configurations.
If the rooms list is empty, size becomes 0, closed is an empty set, and keys starts with [0]. The loop attempts to process index 0, which is not present in closed, so no changes occur and keys is cleared. The final return evaluates not closed as True, which aligns with the interpretation that there are no rooms to visit.
Performance Optimizations
The algorithm uses a set for closed, providing O(1) average-time checks for membership and O(1) removal operations. This choice avoids linear scans that would be required if a list were used to track unopened rooms.
Appending new keys directly to the existing keys list (keys += rooms[open]) leverages Python’s list extension, which is amortized constant time per element. By discarding rooms immediately after processing, the algorithm prevents revisiting the same room, ensuring that each room’s keys are examined at most once.
The use of closed.discard(open) rather than remove avoids raising an exception if the room has already been removed, allowing the code to remain concise while safely handling repeated attempts to open the same room.
Overall, the combination of a set for fast membership tests and in-place list extension for key accumulation yields an efficient traversal that scales well with the number of rooms and keys.
ELI5 - Simplified Explanation
Imagine a big house filled with many locked rooms. Outside the front door, there is a special box that holds a key to one of the other rooms. To start exploring, you pick up the key from that box and walk into the first room. Inside that room, you find more keys tucked away in corners. Each key belongs to a different door in the house.
To see every single room, you collect all the keys you find and put them in your pocket. Whenever you find a new key, you use it to open a new door. Once you are inside that room, you look for even more keys. You keep doing this over and over, moving from room to room using the keys you have collected. If you manage to find a key for every door in the house, you can visit every spot. If you run out of keys but there are still doors left that you have not opened, it means some rooms stay locked away.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | |||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|
| author | solutions | ||||||||||
| www | AlgoMonster | C++ | Python | Java | TS | ||||||
| WalkCCC | C++ | Python | Java | ||||||||
| leetcode.ca | C++ | Python | Java | Rust | Go | TS | |||||
| LeetcodeHelp | C++ | Python | Java | ||||||||
| Progiez | C++ | Python | Java | ||||||||
| github | BigEggStudy | C# | |||||||||
| black-shadows | C++ | ||||||||||
| chandansgowda | Python | ||||||||||
| charles-wangkai | Java | ||||||||||
| DimitrisJim | JS | ||||||||||
| everthis | JS | ||||||||||
| fartem | Ruby | ||||||||||
| fengvyi | C++ | ||||||||||
| fsq | C++ | ||||||||||
| halfrost | Go | ||||||||||
| JoshCrozier | JS | ||||||||||
| Krazune | C++ | ||||||||||
| lkwq007 | Python | ||||||||||
| ruoru | Rust | ||||||||||
| shreymehul | C# | ||||||||||
| suxrobGM | C# | ||||||||||
| trung-hn | Python | ||||||||||
| varunu28 | Java | ||||||||||
| vthwang | Java | ||||||||||
| yuanliu666 | Kotlin | ||||||||||
| YuriSpiridonov | Python | ||||||||||
| zfang399 | C++ | ||||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||||
| WalkCCC | C++, Python, Java | ||||||||||
| leetcode.ca | C++, Go, Java, Python, Rust, TypeScript | ||||||||||
| LeetcodeHelp | C++, Java, Python | ||||||||||
| Progiez | C++, Java, Python | ||||||||||
| BigEggStudy | C# | ||||||||||
| black-shadows | C++, C++ | ||||||||||
| chandansgowda | Python | ||||||||||
| charles-wangkai | Java | ||||||||||
| DimitrisJim | JavaScript | ||||||||||
| everthis | JavaScript | ||||||||||
| fartem | Ruby | ||||||||||
| fengvyi | C++ | ||||||||||
| fsq | C++ | ||||||||||
| halfrost | Go | ||||||||||
| JoshCrozier | JavaScript | ||||||||||
| Krazune | C++ | ||||||||||
| lkwq007 | Python | ||||||||||
| ruoru | Rust | ||||||||||
| shreymehul | C# | ||||||||||
| suxrobGM | C# | ||||||||||
| trung-hn | Python | ||||||||||
| varunu28 | Java | ||||||||||
| vthwang | Java | ||||||||||
| yuanliu666 | Kotlin | ||||||||||
| YuriSpiridonov | Python | ||||||||||
| zfang399 | C++ |
Videos
Similar Problems
- problem 261: Graph Valid Tree
Solved On The Same Day
- problem 521: Longest Uncommon Subsequence I
- problem 557: Reverse Words in a String III
- problem 697: Degree of an Array
- problem 771: Jewels and Stones
- problem 819: Most Common Word
- problem 1700: Number of Students Unable to Eat Lunch
- problem 2073: Time Needed to Buy Tickets
- problem 399: Evaluate Division
- problem 435: Non-overlapping Intervals
- problem 547: Number of Provinces
- problem 1466: Reorder Routes to Make All Paths Lead to the City Zero
- problem 2462: Total Cost to Hire K Workers
- problem 2542: Maximum Subsequence Score
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality