Problem 588464 · medium · Phase 05 Advanced Algorithms & Graphs

Unlock Every Room

graphs · DFS · reachability

There are n rooms labelled 0 .. n-1. All rooms except room 0 start locked. rooms[i] is the list of keys lying in room i; a key labelled j opens room j. You start in room 0, may pick up every key you see, and may walk freely between rooms you have unlocked. Return True if you can enter every room, otherwise False.

Examples

Input:  rooms = [[1],[2],[3],[]]
Output: True
Explanation: room 0 has key 1, room 1 has key 2, room 2 has key 3.

Input:  rooms = [[1,3],[3,0,1],[2],[0]]
Output: False
Explanation: the only key to room 2 is inside room 2.

Constraints

  • 1 <= n <= 2000, total number of keys <= 5000
  • Keys may repeat; a room may contain its own key.
  • Target O(n + keys) time.

Goals

  • Model 'keys found in a room' as directed edges
  • Check whether a search from a start node reaches all nodes
Starting Python…