AAlgoLoopSpaced repetition for LeetCode
MEDIUMBFS / DFSLeetCode ↗

Keys and Rooms

The key idea

Treat each room as a graph node and each key as a directed edge to the room it unlocks. Starting from room 0, run a graph search and count how many distinct rooms you can reach. You can visit every room exactly when that reachable count equals the total number of rooms.

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, but you cannot enter a locked room without holding its key. When you visit a room you may find a set of distinct keys in it; each key is numbered with the room it unlocks, and you may carry every key you find to open other rooms. Given an array rooms where rooms[i] is the set of keys found in room i, return true if you can visit all the rooms, or false otherwise.

Constraints

Examples

Input: rooms = [[1],[2],[3],[]] Output: true
Input: rooms = [[1,3],[3,0,1],[2],[0]] Output: false

Complexity

Time: O(n + e) Space: O(n)

See the full solution

410310
Step-by-step visualization
Start free →

More BFS / DFS problems