MediumNo. 0841

Keys and Rooms — LeetCode 841 Python Solution

Topics
Depth-First Search, Breadth-First Search, Graph
On a study list
LeetCode 75
Reading time
2 min

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

PythonSolution
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

Related problems
No.ProblemDifficulty
0207Course ScheduleMedium
0210Course Schedule IIMedium
0310Minimum Height TreesMedium
0399Evaluate DivisionMedium
0547Number of ProvincesMedium
0684Redundant ConnectionMedium

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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.