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]
Example 1
Output: true
Explanation: room 0 holds key 1, room 1 holds key 2, and room 2 holds key 3.
Example 2
Output: false
Explanation: the only key to room 2 lies inside room 2.
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.
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 booleanopened
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, ArrayDequepushpop
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
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
Java Solution
The method canVisitAllRooms
- First, create the array
, with one flag per room, and an emptyopened namedArrayDeque . Mark room 0 instack , setopened to 1, and push 0 ontocount .stack - While
is not empty, pop the top room intostack , and look at each key inroom with arooms.get(room) loop.for - For a key to a room that is not yet in
, mark that room, add one toopened , and push the room ontocount . Keys to rooms already marked are skipped.stack - When
is empty, return whetherstack equalscount .rooms.size()
The mainint[][]build
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:
[[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 falsecount[[]] -> true
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
The line opened[0] = truetruefalse
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
keeps one flag per room, and each room goes ontoopened once, when it is unlocked, so the stack holds at most n rooms.stack
Searching the newest open room first, as the stack does here, is explained in general in