oneby7

Graphs Graph basics

432. Keys and Rooms

Medium

There are n rooms, numbered from 0 to n - 1. Room 0 is open, and every other room is locked. rooms[i] lists the keys lying in room i. A key with the number k opens room k.

You start in room 0. When you enter a room, you pick up all of its keys. You can walk back to any room you have already opened, and a key opens its room for good.

Return true if you can enter every room, and false if some room stays locked.

Example 1

01234

Input: rooms = [[2, 3], [], [1], [4, 0], []]

Output: true

Explanation: Room 0 holds the keys to rooms 2 and 3. Room 2 holds the key to room 1, and room 3 the key to room 4. So all five rooms open.

Example 2

0123

Input: rooms = [[1], [0, 1], [3], [2]]

Output: false

Explanation: Rooms 0 and 1 hold only keys to each other. Rooms 2 and 3 hold each other's keys, but both are locked, so we never get inside.

Example 3

0

Input: rooms = [[]]

Output: true

Explanation: The only room is room 0, and it is open.

Check your understanding

Work out the answer for this input before you write any code.

rooms = [[2], [], [1, 3], []]

Constraints

  • 1 ≤ n == rooms.length ≤ 105
  • 0 ≤ rooms[i][j] < n
  • All the rooms together hold at most 2 × 105 keys.

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.