Keys and Rooms

There are n rooms labeled 0 to n - 1. Every room except room 0 starts locked. Room i holds a set of keys, rooms[i], and each key opens the room with that number. You start in room 0, and whenever you enter a room you can take all of its keys. Return true if you can visit every room, otherwise false.

30:00

Keys and Rooms
medium
Free written solution
Topics
Companies

There are n rooms labeled 0 to n - 1. Every room except room 0 starts locked. Room i holds a set of keys, rooms[i], and each key opens the room with that number. You start in room 0, and whenever you enter a room you can take all of its keys. Return true if you can visit every room, otherwise false.

Example 1:
Input: {"rooms":[[1],[2],[3],[]]}
Output: true
Constraints:
  • n==rooms.lengthn == \text{rooms.length}

  • 2≤n≤10002 \leq n \leq 1000

  • 0≤rooms[i].length≤10000 \leq \text{rooms}[i].\text{length} \leq 1000

  • 1≤∑rooms[i].length≤30001 \leq \sum \text{rooms}[i].\text{length} \leq 3000

  • 0≤rooms[i][j]<n0 \leq \text{rooms}[i][j] < n

  • All the values of rooms[i]\text{rooms}[i] are unique.

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"rooms":[[1],[2],[3],[]]}

4 rooms. Only room 0 is open; every other door needs its key.

room 0

1

locked

room 1

2

locked

room 2

3

locked

room 3

no keys

locked

stack (top on the right)

empty

rooms unlocked

0 / 4

room being searched
unlocked, waiting
searched
key
Variables
VariableValue
stack[]
seen0
n4
DepthFunction Call
Stack empty
0/9