Skip to content

Open Every Locked Room

Easy#dfs#reachability~15 min

The mission

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

Target time
O(n + k)
Target space
O(n)

Constraints

  • n ≤ 1000 rooms
  • ≤ 3000 keys in total
  • room 0 starts open

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

Python 3Ctrl+Enter runs
Custom test case