Keys and Rooms

Start in room 0, pick up the keys you find, and decide whether every room can be opened.

There are n rooms, numbered 0 to n - 1. Room 0 is unlocked and every other room is locked. Each room holds some keys: rooms[i] lists the keys inside room i, and the key numbered k opens room k. Return true if you can enter every room, and false otherwise.

Example 1
Input: rooms = [[1], [2], [3], []]
Output: true
Explanation: room 0 holds key 1, room 1 holds key 2, and room 2 holds key 3.
Example 2
Input: rooms = [[1, 3], [3, 0, 1], [2], [0]]
Output: false
Explanation: the only key to room 2 lies inside room 2.
Solution

The Idea

Think of an escape room game: you start in one open room, and every key you pick up opens another door. Here the rooms are numbered, and each key carries the number of the room it opens. In Example 1, room 0 holds key 1, room 1 holds key 2 and room 2 holds key 3, so you walk through all four rooms in a line.

Example 2 is less tidy. Room 0 holds keys 1 and 3, so both of those doors open. Room 3 holds only key 0, to the room you started in. Room 1 holds keys 3, 0 and 1, all to rooms that are already open. Room 2 holds key 2, but that key lies inside room 2 itself, so its door never opens.

Two questions come up. Many keys lead back to rooms that are already open: room 0 gives key 1, and room 1 gives key 0 again. How do we avoid going round in circles? And when one room opens several doors at once, which room do we search next?

Look at the picture below. Each box is a room of Example 2, with the keys it holds written inside, and each arrow goes from a room to another room that one of its keys opens.

Example 2 as rooms and arrows. Room 0, marked start here, has blue arrows labelled key 1 to room 1 and key 3 to room 3. Grey arrows from room 1 and room 3 lead back to rooms already reached. Room 2, with a dashed orange border, has no arrow coming in.

Room 0, marked "start here", has two blue arrows, labelled key 1 and key 3. They already reach room 1 and room 3. The grey arrows, from room 1 and room 3, only point at rooms that are already open: room 0, where we started, and room 3. A key to a room's own door, such as key 1 in room 1, gets no arrow. Room 2, with the dashed orange border, has no arrow coming in at all.

Boxes joined by one-way arrows like this form a directed graph: the rooms are its vertices, and each arrow is an edge. The puzzle becomes a question about the picture: starting from room 0 and following arrows, can we reach every room? Only the first key found to a room matters, and every later copy can be ignored.

Solution Approach

Turning that idea into code means settling four things: how to remember which rooms are open, which open room to search next, when to count a room, and how to read the answer at the end.

Remembering which rooms are open

How do we stop going round in circles? Keep one true or false flag per room, in a boolean array named opened. A key whose room is already marked is skipped, so each room is entered and searched only once. Room 0 is marked before the search starts, since we stand in it without needing a key.

Choosing the next room to search

When room 0 opens rooms 1 and 3 together, which goes first? For the answer it does not matter, because both get searched before the end. A stack is a simple place to hold them. Like a pile of plates, it gives back the last item put on first: each newly opened room is pushed on top, and the next room to search is popped from the top.

Always searching the newest room first, and so going deeper before going back, is called a depth-first search. In Java, ArrayDeque is a resizable array that can add and remove at either end, and its push and pop methods make it work as a stack. A queue, which gives items back in the order they went in, would search the rooms in the order they opened. That is a breadth-first search, and it gives the same answer.

Counting the open rooms

When should a room be counted? At the moment its key is first found, together with setting its flag. A counter named count then always holds the number of open rooms, and it starts at 1 for room 0. Marking a room as soon as it is unlocked, not later when it is searched, also means that a room whose key lies in several rooms is pushed only once.

Reading the answer

When is the search over? When the stack is empty, every open room has been searched and there is no key left to try. If count equals the number of rooms, every door was opened. Otherwise some room, like room 2 in Example 2, has no key in any room we could reach.

Java Solution

The method canVisitAllRooms works in these steps:

  1. First, create the array opened, with one flag per room, and an empty ArrayDeque named stack. Mark room 0 in opened, set count to 1, and push 0 onto stack.
  2. While stack is not empty, pop the top room into room, and look at each key in rooms.get(room) with a for loop.
  3. For a key to a room that is not yet in opened, mark that room, add one to count, and push the room onto stack. Keys to rooms already marked are skipped.
  4. When stack is empty, return whether count equals rooms.size().

The main method builds each input from a small int[][] with a helper named build. It runs both examples, a single room with no keys, a case where room 0 holds two copies of key 2, and two pairs of rooms whose keys only open each other.

Java
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.List;

public class KeysAndRooms {

    public static boolean canVisitAllRooms(List<List<Integer>> rooms) {
        boolean[] opened = new boolean[rooms.size()];
        Deque<Integer> stack = new ArrayDeque<>();
        opened[0] = true;                     // we start inside room 0
        int count = 1;
        stack.push(0);
        while (!stack.isEmpty()) {
            int room = stack.pop();           // search this room for keys
            for (int key : rooms.get(room)) {
                if (!opened[key]) {           // a key to a room still locked
                    opened[key] = true;
                    count++;
                    stack.push(key);
                }
            }
        }
        return count == rooms.size();
    }

    static List<List<Integer>> build(int[][] keys) {
        List<List<Integer>> rooms = new ArrayList<>();
        for (int[] room : keys) {
            List<Integer> list = new ArrayList<>();
            for (int k : room) {
                list.add(k);
            }
            rooms.add(list);
        }
        return rooms;
    }

    static void run(int[][] keys) {
        List<List<Integer>> rooms = build(keys);
        System.out.println(rooms + " -> " + canVisitAllRooms(rooms));
    }

    public static void main(String[] args) {
        run(new int[][] {{1}, {2}, {3}, {}});
        run(new int[][] {{1, 3}, {3, 0, 1}, {2}, {0}});
        run(new int[][] {{}});
        run(new int[][] {{2, 2}, {}, {1}});
        run(new int[][] {{1}, {0}, {3}, {2}});
    }
}

Running it prints:

Output
[[1], [2], [3], []] -> true
[[1, 3], [3, 0, 1], [2], [0]] -> false
[[]] -> true
[[2, 2], [], [1]] -> true
[[1], [0], [3], [2]] -> false

Example 2 gives false on the second line: room 0 opens rooms 1 and 3, neither of them holds a new key, and count stops at 3 of 4. The line [[]] -> true is a house of a single room, which counts as open from the start, so no key is needed.

On the fourth line, room 0 holds key 2 twice. The second copy finds room 2 already marked and is skipped, and the key 1 inside room 2 opens the last room. The last line is false because rooms 0 and 1 hold only keys to each other, so rooms 2 and 3 never open.

The line opened[0] = true before the loop matters. With it removed, the search on Example 2 reaches room 3, finds key 0 and counts room 0 a second time. The count reaches 4 while room 2 is still locked, and that version returns true instead of false.

Complexity

The search enters each room at most once and reads each key once.

  • Time: O(n + m) for n rooms holding m keys in total, because each room is pushed and popped at most once, and popping a room reads each of its keys once.
  • Space: O(n), because opened keeps one flag per room, and each room goes onto stack once, when it is unlocked, so the stack holds at most n rooms.

Searching the newest open room first, as the stack does here, is explained in general in Depth First Search.