Keys and Rooms

Medium Graphs BFS / DFS Basics

Keys and Rooms is a medium graphs problem solved with the bfs / dfs basics pattern. The best approach, optimal (breadth-first search with a queue), runs in O(n + K) time and O(n) space. Below are 3 approaches in Java, Python, C++ and JavaScript, from brute force (sweep until nothing changes) up.

Problem

There are n rooms, numbered 0 to n - 1. Every room is locked except room 0, which is where you start.

Inside each room you may find some keys. Each key is labeled with the number of the room it opens. When you enter a room you can pick up all of its keys and use them later, as often as you like. You can only enter a room once you hold its key (room 0 needs none).

You are given rooms, where rooms[i] lists the keys lying in room i. Return true if you can enter every room, and false otherwise.

Examples

Example 1

Input
rooms = [[1, 3], [2], [], [0]]
Output
true
Why
Room 0 is open and holds the keys to rooms 1 and 3. Room 1 holds the key to room 2. That covers all four rooms. Room 3's key to room 0 is not needed, since room 0 is already open.

Example 2

Input
rooms = [[1], [0, 2], [], [2]]
Output
false
Why
From room 0 you reach room 1, and from room 1 you reach room 2. No room holds a key to room 3, so it stays locked. The key inside room 3 does not help, since you can never get in to pick it up.

Example 3

Input
rooms = [[3], [2], [1], []]
Output
false
Why
Room 0 opens room 3, which is empty. The key to room 1 lies in room 2 and the key to room 2 lies in room 1, so neither can ever be opened first.

Constraints

  • n == rooms.length
  • 2 <= n <= 1000
  • 0 <= rooms[i].length <= 1000
  • 1 <= sum(rooms[i].length) <= 3000
  • 0 <= rooms[i][j] < n
  • The keys inside one room are all different.

Solve it here

Write your solution in Java, Python, C++ or JavaScript and run it against the examples, right in the page. Submit runs the hidden tests too and, with a free account, records the solve in your revision log.

00:00
Testcase

Run checks the testcases above (3 examples, or your own). Submit also runs 38 hidden tests and saves the solve to your log. Signed in, every Run and Submit is saved under My submissions; your draft stays in this browser.

Animated walkthrough

A narrated, step-by-step animation that builds the solution from the idea up. Press play, or step through it at your own pace.

Concepts first, then the problem and every approach, step by step.

Space to play or pause · ← → to jump a step · click or drag the bar to seek

Solutions

Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the code in Java, Python, C++ and JavaScript.

ApproachTimeSpace
Brute force (sweep until nothing changes)O(n · (n + K))O(n)
Depth-first search (recursion)O(n + K)O(n)
Optimal (breadth-first search with a queue)O(n + K)O(n)

1Brute force (sweep until nothing changes)

TimeO(n · (n + K))With K keys in total, one sweep looks at all n rooms and their keys, which is O(n + K). Each sweep except the last opens at least one room, so there are at most n sweeps.
SpaceO(n)Only the array of n open flags.

Simulate it the naive way. Keep a flag for every room saying whether it is open; at first only room 0 is. Sweep over all open rooms and open every room whose key you find. A key found late in a sweep may open a room that the sweep has already passed, so repeat the sweeps until one of them opens nothing new. At that point every reachable room is open, and the answer is whether all flags are set.

  1. Set open[0] = true.
  2. Repeat while the last sweep changed something: for every open room i, and every key k in it, if room k is closed, open it and remember that something changed.
  3. Return true exactly when every room is open.
class Solution {
    public boolean canVisitAllRooms(List<List<Integer>> rooms) {
        int n = rooms.size();
        boolean[] open = new boolean[n];
        open[0] = true;
        boolean changed = true;
        while (changed) {
            changed = false;
            for (int i = 0; i < n; i++) {
                if (!open[i]) continue;
                for (int key : rooms.get(i)) {
                    if (!open[key]) {
                        open[key] = true;
                        changed = true;
                    }
                }
            }
        }
        for (boolean o : open) {
            if (!o) return false;
        }
        return true;
    }
}

2Depth-first search (recursion)

TimeO(n + K)Each room is entered at most once, and each key is looked at once, when its room is entered.
SpaceO(n)The seen array, plus a call stack that can be n deep when the rooms form a chain.

Treat the rooms as a directed graph, where a key in room u is an edge from u to the room it opens. Walk into room 0, mark it as seen, and for every key whose room has not been seen yet, walk into that room the same way. Each call returns how many rooms it newly entered, itself included. All rooms can be visited exactly when the call on room 0 counts n rooms.

  1. Create seen of size n.
  2. visit(room): mark room seen, set count = 1, and for each key in the room whose room is not seen, add visit(key) to count. Return count.
  3. Return visit(0) == n.
class Solution {
    public boolean canVisitAllRooms(List<List<Integer>> rooms) {
        boolean[] seen = new boolean[rooms.size()];
        return visit(rooms, 0, seen) == rooms.size();
    }

    private int visit(List<List<Integer>> rooms, int room, boolean[] seen) {
        seen[room] = true;
        int count = 1;
        for (int key : rooms.get(room)) {
            if (!seen[key]) count += visit(rooms, key, seen);
        }
        return count;
    }
}

3Optimal (breadth-first search with a queue)

TimeO(n + K)Each room enters the queue at most once and each key is read once.
SpaceO(n)The seen array and the queue hold at most n rooms.

The same graph search, done with a queue instead of recursion, so the depth of the room chain does not matter. Put room 0 in the queue and mark it seen. Take rooms out one at a time; for each key inside, if its room is not seen yet, mark it, count it and queue it. Marking a room when its key is first found, not when it is taken out, guarantees that no room enters the queue twice. At the end, compare the count with n.

  1. Mark room 0 seen, put it in the queue, and set visited = 1.
  2. While the queue is not empty, take out a room.
  3. For each key in it: if key is not seen, mark it, add one to visited, and add it to the queue.
  4. Return visited == n.
class Solution {
    public boolean canVisitAllRooms(List<List<Integer>> rooms) {
        int n = rooms.size();
        boolean[] seen = new boolean[n];
        Deque<Integer> queue = new ArrayDeque<>();
        queue.add(0);
        seen[0] = true;
        int visited = 1;
        while (!queue.isEmpty()) {
            int room = queue.poll();
            for (int key : rooms.get(room)) {
                if (!seen[key]) {
                    seen[key] = true;
                    visited++;
                    queue.add(key);
                }
            }
        }
        return visited == n;
    }
}

Edge cases to test

  • Room 0 is empty: no other room can be opened, so the answer is false
  • Keys to rooms that are already open, including room 0 itself, must not cause endless loops
  • A room's only key is inside that same room: it can never be opened
  • Two rooms that hold each other's keys and nothing else points to them: both stay locked
  • A long chain 0 -> 1 -> 2 -> ... -> n - 1: a recursive search goes n calls deep
  • Every key sits in room 0: one step opens everything

Hints

Hint 1

Think of each room as a node and each key as a directed edge from the room it lies in to the room it opens.

Hint 2

The question becomes: starting from node 0, can you reach every node?

Hint 3

Any graph search works. Mark a room as visited the moment you first get its key, so no room is processed twice, then count the visited rooms.

FAQ

What is the best time complexity for Keys and Rooms?

Optimal (breadth-first search with a queue) runs in O(n + K) time and O(n) extra space. Each room enters the queue at most once and each key is read once.

Which pattern does Keys and Rooms use?

It is a graphs problem that uses the bfs / dfs basics pattern. Other problems with the same pattern: BFS - Normal + Level by Level, DFS - Recursive + Iterative, Clone Graph.

Is there a brute force solution for Keys and Rooms?

Yes. Brute force (sweep until nothing changes) takes O(n · (n + K)) time and O(n) space. Simulate it the naive way.

Which edge cases should I test for Keys and Rooms?

Room 0 is empty: no other room can be opened, so the answer is false; Keys to rooms that are already open, including room 0 itself, must not cause endless loops; A room's only key is inside that same room: it can never be opened; Two rooms that hold each other's keys and nothing else points to them: both stay locked; A long chain 0 - 1 - 2 - ... - n - 1: a recursive search goes n calls deep; Every key sits in room 0: one step opens everything.