[LeetCode] Keys and Rooms

841. Keys and Rooms

There are N rooms and you start in room 0. Each room has a distinct number in 0, 1, 2, …, N-1, and each room may have some keys to access the next room.

Formally, each room i has a list of keys rooms[i], and each key rooms[i][j] is an integer in [0, 1, …, N-1] where N = rooms.length. A key rooms[i][j] = v opens the room with number v.

Initially, all the rooms start locked (except for room 0).

You can walk back and forth between rooms freely.

Return true if and only if you can enter every room.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class Solution {
public:
bool canVisitAllRooms(vector<vector<int>>& rooms) {
int visit = 1;
queue<int> keys;
vector<bool> v(rooms.size(), false);
v[0] = true;
for(auto key : rooms[0])
if(!v[key]){
keys.push(key);
v[key] = true;
visit++;
}

while(!keys.empty()) {
auto key = keys.front();
keys.pop();
for(auto key : rooms[key])
if(!v[key]){
keys.push(key);
v[key] = true;
visit++;
}
}
return visit == rooms.size();
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2021/03/19/PS/LeetCode/keys-and-rooms/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.