Skip to content
BytePatterns

Open Every Locked Room

EasyGraphs#dfs#reachability~15m

Problem

An escape room has n rooms numbered 0 to n - 1. Room 0 is open and every other room starts locked. Inside room i lies a list of keys, rooms[i], and a key with number j opens room j. Keys can be used any number of times and in any order. Return True if you can get into every room. There are up to 1,000 rooms and up to 3,000 keys in total.

Examples

Input:  rooms = [[1], [2], [3], []]
Output: True
Why:    room 0 holds key 1, room 1 holds key 2, room 2 holds key 3
Input:  rooms = [[1, 3], [3, 0, 1], [2], [0]]
Output: False
Why:    the only key to room 2 is locked inside room 2 itself
Input:  rooms = [[]]
Output: True
Why:    edge case, the only room is already open

Hints

0 / 3

Stuck on the idea rather than the code? Depth-First Search covers it.