-
Notifications
You must be signed in to change notification settings - Fork 110
/
Copy path841-keys-and-rooms.cpp
61 lines (53 loc) · 1.45 KB
/
841-keys-and-rooms.cpp
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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
// Recursive DFS
class Solution {
public:
void openRooms(vector<vector<int>>& rooms, int i, vector<bool>& opened) {
if (opened[i]) return;
opened[i] = true;
for (int& n : rooms[i]) {
openRooms(rooms, n, opened);
}
}
bool canVisitAllRooms(vector<vector<int>>& rooms) {
int n = rooms.size();
vector<bool> opened(n, false);
openRooms(rooms, 0, opened);
for (bool val : opened) {
if (!val) return false;
}
return true;
}
};
// Iterative DFS
#include <stack>
class Solution {
public:
void openRooms(vector<vector<int>>& rooms, int i, vector<bool>& opened) {
stack<int> s;
s.push(i);
while (!s.empty()) {
int currRoom = s.top();
s.pop();
for (auto& n : rooms[currRoom]) {
if (!opened[n]) {
s.push(n);
opened[n] = true;
}
}
}
}
bool canVisitAllRooms(vector<vector<int>>& rooms) {
int n = rooms.size();
vector<bool> opened(n, false);
opened[0] = true;
for (int i = 0; i < n; i++) {
if (opened[i]) {
openRooms(rooms, i, opened);
}
}
for (bool val : opened) {
if (!val) return false;
}
return true;
}
};