871. Keys and Rooms
MediumSolutions in Python, Java, C++, TypeScript
Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.
Approach
Method: Graph Traversal (BFS)
This problem can be modeled as a graph problem. Each room is a node, and the keys inside a room represent directed edges to other nodes.
Solution
Keys and Rooms in Python
import collections
class Solution:
def canVisitAllRooms(self, rooms: list[list[int]]) -> bool:
n = len(rooms)
if n == 0:
return True
# Use a set to keep track of visited rooms for O(1) lookups.
visited = {0}
# Use a deque as an efficient queue for BFS.
queue = collections.deque([0])
# Perform BFS.
while queue:
current_room = queue.popleft()
# Iterate through the keys in the current room.
for key in rooms[current_room]:
# If the room unlocked by the key has not been visited yet.
if key not in visited:
visited.add(key) # Mark as visited.
queue.append(key) # Add to the queue to visit later.
# If the number of visited rooms equals the total number of rooms, return true.
return len(visited) == n
Keys and Rooms in Java
class Solution {
public boolean canVisitAllRooms(List<List<Integer>> rooms) {
int n = rooms.size();
if (n == 0) {
return true;
}
// visited[i] will be true if room i has been visited.
boolean[] visited = new boolean[n];
// Queue for BFS.
Queue<Integer> queue = new LinkedList<>();
// Start from room 0.
visited[0] = true;
queue.add(0);
int visitedCount = 1; // Count of visited rooms.
// Perform BFS.
while (!queue.isEmpty()) {
int currentRoom = queue.poll();
// Iterate through the keys in the current room.
for (int key : rooms.get(currentRoom)) {
// If the room unlocked by the key has not been visited yet.
if (!visited[key]) {
visited[key] = true; // Mark as visited.
queue.add(key); // Add to the queue to visit later.
visitedCount++; // Increment the visited rooms count.
}
}
}
// If the count of visited rooms is equal to the total number of rooms, return true.
return visitedCount == n;
}
}
Keys and Rooms in C++
class Solution {
public:
bool canVisitAllRooms(vector<vector<int>>& rooms) {
int n = rooms.size();
if (n == 0) {
return true;
}
// visited[i] will be true if room i has been visited.
vector<bool> visited(n, false);
// Queue for BFS.
queue<int> q;
// Start from room 0.
visited[0] = true;
q.push(0);
int count = 1; // Count of visited rooms.
// Perform BFS.
while (!q.empty()) {
int current_room = q.front();
q.pop();
// Iterate through the keys in the current room.
for (int key : rooms[current_room]) {
// If the room unlocked by the key has not been visited yet.
if (!visited[key]) {
visited[key] = true; // Mark as visited.
q.push(key); // Add to the queue to visit later.
count++; // Increment the visited rooms count.
}
}
}
// If the count of visited rooms is equal to the total number of rooms, return true.
return count == n;
}
};
Keys and Rooms in TypeScript
function canVisitAllRooms(rooms: number[][]): boolean {
const n = rooms.length;
if (n === 0) {
return true;
}
// Use a Set to keep track of visited rooms for O(1) lookups.
const visited = new Set<number>();
// Use an array as a queue for BFS.
const queue: number[] = [];
// Start from room 0.
visited.add(0);
queue.push(0);
let head = 0; // Use a pointer for the queue to avoid slow shift()
// Perform BFS.
while (head < queue.length) {
const currentRoom = queue[head];
head++;
// Iterate through the keys in the current room.
for (const key of rooms[currentRoom]) {
// If the room unlocked by the key has not been visited yet.
if (!visited.has(key)) {
visited.add(key); // Mark as visited.
queue.push(key); // Add to the queue to visit later.
}
}
}
// If the number of visited rooms equals the total number of rooms, return true.
return visited.size === n;
};
More Medium LeetCode answers
Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.
LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.