Keys and Rooms

Medium#841graph

There are n locked rooms numbered from 0, and only room 0 is open. Each room has some keys lying in it, each opening one room. Find out whether you can get into every room. Our example: the keys in rooms 0 to 4 are [1, 3], [3, 0], [4], [], [2] — the answer is false.

input
rooms: n rooms numbered from 0, all locked but room 0. rooms[i] are the keys lying in room i: a key k opens room k.
returns
true if you can get into every room, taking the keys from the rooms you have opened; otherwise false.
constraints
  • n = rooms.length, 2 ≤ n ≤ 400
  • 0 ≤ rooms[i][j] < n
  • the keys in a room are all different
  • 1 ≤ sum(rooms[i].length) ≤ 2000
our 12 tests keep to them
examples
Open a test in the tests panel: it shows the input and the expected answer.
/**
 * @param {number[][]} rooms
 * @return {boolean}
 */
function canVisitAllRooms(rooms) {

}
Ctrl ↵
format
reset

saved in this browser

12 tests · limit 3 s

Stuck?

See the solution run step by step on our example, then why it works and its complexity.

Watch the walkthrough →

Next: more breadth-first search (bfs) problems

Pattern “Breadth-first search (BFS)” →

The problem and its statement belong to LeetCode. Here are our own retelling, example and solution. Patterns Hero is not affiliated with LeetCode.