Approach
Breadth-first search
For Minimum Jumps to Reach Home, 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
- 36 lines of Java from the credited upstream file 1654.java.
- The implementation visibly relies on sequence storage, hash lookup, ordered lookup, 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.
1enum Direction { FORWARD, BACKWARD }2 3class Solution {4 public int minimumJumps(int[] forbidden, int a, int b, int x) {5 int furthest = x + a + b;6 Set<Integer> seenForward = new HashSet<>();7 Set<Integer> seenBackward = new HashSet<>();8 9 for (final int pos : forbidden) {10 seenForward.add(pos);11 seenBackward.add(pos);12 furthest = Math.max(furthest, pos + a + b);13 }14 15 16 Queue<Pair<Direction, Integer>> q = new ArrayDeque<>(List.of(new Pair<>(Direction.FORWARD, 0)));17 18 for (int ans = 0; !q.isEmpty(); ++ans)19 for (int sz = q.size(); sz > 0; --sz) {20 Direction dir = q.peek().getKey();21 final int pos = q.poll().getValue();22 if (pos == x)23 return ans;24 final int forward = pos + a;25 final int backward = pos - b;26 if (forward <= furthest && seenForward.add(forward))27 q.offer(new Pair<>(Direction.FORWARD, forward));28 29 if (dir == Direction.FORWARD && backward >= 0 && seenBackward.add(backward))30 q.offer(new Pair<>(Direction.BACKWARD, backward));31 }32 33 return -1;34 }35}36