1061. Keys and Rooms

MediumGraphsDFSBFSGraph

There are n rooms labeled 0..n-1, all locked except room 0. rooms[i] is a list of keys you obtain by visiting room i, each key opening the room of that number. Starting in room 0, determine whether you can visit all rooms. Return true or false. The input is JSON {rooms}.

Input: JSON {rooms}.

Output: Boolean — true or false.

Examples

Example 1
Input: {"rooms":[[1],[2],[3],[]]}
Output: true
Explanation: Keys chain through all rooms.
Example 2
Input: {"rooms":[[1,3],[3,0,1],[2],[0]]}
Output: false
Explanation: Room 2 is never reachable.
Example 3
Input: {"rooms":[[]]}
Output: true
Explanation: Only room 0.

Constraints

Asked by

AppleOracleGoogleAmazonMicrosoftMeta
Solve this problem in the editor →