Approach
Breadth-first search
For Maximum Candies You Can Get from Boxes, the implementation explores reachable states in layers, which is the standard shape for unweighted shortest paths and minimum-step transitions.
- Model each valid configuration as a state and each legal move as an edge.
- Seed the queue with the starting state and mark it immediately.
- Expand each state once, recording distance or reachability for unseen neighbours.
Code notes
- 43 lines of C++ from the credited upstream file 1298.cpp.
- The implementation visibly relies on sequence storage, work queue.
- 3 loop blocks detected.
Complexity
Verify that each state and transition is processed only a bounded number of times; that determines the traversal cost.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public:3 int maxCandies(vector<int>& status, vector<int>& candies,4 vector<vector<int>>& keys, vector<vector<int>>& containedBoxes,5 vector<int>& initialBoxes) {6 int ans = 0;7 queue<int> q;8 vector<bool> reachedClosedBoxes(status.size());9 10 auto pushBoxesIfPossible = [&status, &q,11 &reachedClosedBoxes](const vector<int>& boxes) {12 for (const int box : boxes)13 if (status[box])14 q.push(box);15 else16 reachedClosedBoxes[box] = true;17 };18 19 pushBoxesIfPossible(initialBoxes);20 21 while (!q.empty()) {22 const int currBox = q.front();23 q.pop();24 25 26 ans += candies[currBox];27 28 29 30 for (const int key : keys[currBox]) {31 if (!status[key] && reachedClosedBoxes[key])32 q.push(key);33 status[key] = 1; 34 }35 36 37 pushBoxesIfPossible(containedBoxes[currBox]);38 }39 40 return ans;41 }42};43