-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathLC1298.cpp
More file actions
executable file
·50 lines (42 loc) · 1.02 KB
/
LC1298.cpp
File metadata and controls
executable file
·50 lines (42 loc) · 1.02 KB
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
/*
Problem Statement: https://leetcode.com/problems/maximum-candies-you-can-get-from-boxes/
*/
class Solution {
public:
int maxCandies(vector<int>& status, vector<int>& candies, vector< vector<int> >& keys, vector< vector<int> >& containedBoxes, vector<int>& initialBoxes) {
int candy, n, box;
candy = 0;
n = status.size();
queue<int> q;
vector<bool> reach(n), visited(n);
// Helper function to process box
auto process = [&](int box) {
if (!visited[box] && status[box] && reach[box]) {
q.push(box);
visited[box] = true;
}
};
// Initialize queue
for (int box: initialBoxes) {
reach[box] = true;
process(box);
}
// Go through all boxes possible
while (!q.empty()) {
box = q.front();
q.pop();
candy += candies[box];
// Go through keys found and unlock
for (int b: keys[box]) {
status[b] = 1;
process(b);
}
// Go through boxes found and mark them reachable
for (int b: containedBoxes[box]) {
reach[b] = true;
process(b);
}
}
return candy;
}
};