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 Python from the credited upstream file 1654.py.
- The implementation visibly relies on sequence storage, work queue.
- No explicit 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.
1from enum import Enum2 3 4class Direction(Enum):5 FORWARD = 06 BACKWARD = 17 8 9class Solution:10 def minimumJumps(self, forbidden: list[int], a: int, b: int, x: int) -> int:11 furthest = max(x + a + b, max(pos + a + b for pos in forbidden))12 seenForward = {pos for pos in forbidden}13 seenBackward = {pos for pos in forbidden}14 15 16 q = collections.deque([(Direction.FORWARD, 0)])17 18 ans = 019 while q:20 for _ in range(len(q)):21 dir, pos = q.popleft()22 if pos == x:23 return ans24 forward = pos + a25 backward = pos - b26 if forward <= furthest and forward not in seenForward:27 seenForward.add(forward)28 q.append((Direction.FORWARD, forward))29 30 if dir == Direction.FORWARD and backward >= 0 and backward not in seenBackward:31 seenBackward.add(backward)32 q.append((Direction.BACKWARD, backward))33 ans += 134 35 return -136