MediumNo. 0841
Keys and Rooms — LeetCode 841 Python Solution
- Pattern
- Breadth-First Search
- Topics
- Depth-First Search, Breadth-First Search, Graph
- On a study list
- LeetCode 75
- Reading time
- 2 min
- Source
- leetcode.com
The problem
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.
Example
- Input
- rooms = [[1],[2],[3],[]]
- Output
- true
- Explanation
- We visit room 0 and pick up key 1.
Python solution
class Solution:
def canVisitAllRooms(self, rooms: List[List[int]]) -> bool:
def dfs(i: int):
if i in vis:
return
vis.add(i)
for j in rooms[i]:
dfs(j)
vis = set()
dfs(0)
return len(vis) == len(rooms)Complexity
- Time
- O(n + m)
- Space · auxiliary
- O(n)where n is the number of nodes, and m is the number of edges
Pattern: Breadth-First Search
Expand outward level by level, so the first time you arrive is the shortest way. LeetCode 841. Keys and Rooms is filed here because LeetCode tags it Breadth-First Search, which is the vocabulary this hub collects.
The breadth-first search guide has the Python template for the pattern and the 233 LeetCode problems that use it.
Related problems
| No. | Problem | Difficulty |
|---|---|---|
| 0207 | Course Schedule | Medium |
| 0210 | Course Schedule II | Medium |
| 0310 | Minimum Height Trees | Medium |
| 0399 | Evaluate Division | Medium |
| 0547 | Number of Provinces | Medium |
| 0684 | Redundant Connection | Medium |
Frequently asked questions
- How hard is LeetCode 841. Keys and Rooms?
LeetCode 841. Keys and Rooms is rated Medium on LeetCode.
- What is the time complexity of LeetCode 841. Keys and Rooms?
The Python solution on this page runs in O(n + m).
- What is the space complexity of LeetCode 841. Keys and Rooms?
The Python solution on this page uses O(n), where n is the number of nodes, and m is the number of edges auxiliary space.
- What topics does LeetCode 841. Keys and Rooms cover?
LeetCode 841. Keys and Rooms is tagged Depth-First Search, Breadth-First Search and Graph on LeetCode.