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
- 40 lines of Java from the credited upstream file 1298.java.
- 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 int maxCandies(int[] status, int[] candies, int[][] keys, int[][] containedBoxes,3 int[] initialBoxes) {4 int ans = 0;5 Queue<Integer> q = new ArrayDeque<>();6 boolean[] reachedClosedBoxes = new boolean[status.length];7 8 pushBoxesIfPossible(initialBoxes, status, q, reachedClosedBoxes);9 10 while (!q.isEmpty()) {11 final int currBox = q.poll();12 13 14 ans += candies[currBox];15 16 17 18 for (final int key : keys[currBox]) {19 if (status[key] == 0 && reachedClosedBoxes[key])20 q.offer(key);21 status[key] = 1; 22 }23 24 25 pushBoxesIfPossible(containedBoxes[currBox], status, q, reachedClosedBoxes);26 }27 28 return ans;29 }30 31 private void pushBoxesIfPossible(int[] boxes, int[] status, Queue<Integer> q,32 boolean[] reachedClosedBoxes) {33 for (final int box : boxes)34 if (status[box] == 1)35 q.offer(box);36 else37 reachedClosedBoxes[box] = true;38 }39}40