There are n
rooms in a building, numbered from 0
to n-1
. Each room might have some keys to access other rooms. Initially, only room 0
is unlocked. You are given an array rooms
where rooms[i]
is a list of keys in the i-th
room. A key rooms[i][j] = v
allows you to open room v
.
You need to determine if you can visit all the rooms starting from room 0
.
The problem can be summarized as:
0
.Example:
Input: rooms = [[1],[2],[3],[]]
Output: true
Explanation:
We begin in room 0, and pick up key 1.
We then go to room 1, and pick up key 2.
We then go to room 2, and pick up key 3.
We then go to room 3. Since we were able to visit every room, we return true.
Input: rooms = [[1,3],[3,0,1],[2],[0]]
Output: false
Explanation:
We can't access room 2 from the given keys.
n
?
n
can be up to 10^4
.rooms
array is empty?
false
since there are no rooms to visit.0
.Here’s the implementation using Depth-First Search (DFS):
#include <vector>
#include <stack>
#include <unordered_set>
class Solution {
public:
bool canVisitAllRooms(std::vector<std::vector<int>>& rooms) {
int n = rooms.size();
std::vector<bool> visited(n, false);
std::stack<int> stack;
stack.push(0);
visited[0] = true;
while (!stack.empty()) {
int room = stack.top();
stack.pop();
for (int key : rooms[room]) {
if (!visited[key]) {
visited[key] = true;
stack.push(key);
}
}
}
for (bool v : visited) {
if (!v) return false;
}
return true;
}
};
0
. Use a stack for DFS traversal.visited
array to mark rooms that have been visited.0
onto the stack and mark it as visited.O(N + E)
where N
is the number of rooms and E
is the number of keys.O(N)
for the visited list and the stack.This approach ensures we properly check if all rooms can be visited starting from room 0
.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?