Minimum Jumps to Reach Home - Problem
Imagine a clever bug trying to navigate its way home on a number line! ๐
The bug starts at position 0 and wants to reach its cozy home at position x. However, this isn't just any ordinary bug - it has some unique movement rules:
- It can jump exactly
apositions forward (to the right) - It can jump exactly
bpositions backward (to the left) - Critical constraint: It cannot jump backward twice in a row (no consecutive backward jumps!)
- Some positions are
forbidden- the bug cannot land on these spots - The bug cannot jump to negative positions
Your mission: Find the minimum number of jumps needed for the bug to reach home at position x. If it's impossible to reach home, return -1.
Note: The bug can jump forward beyond its home and then come back if needed!
Input & Output
example_1.py โ Basic case
$
Input:
forbidden = [14,4,18,1,15], a = 3, b = 15, x = 9
โบ
Output:
3
๐ก Note:
The bug can reach home in 3 jumps: 0 -> 3 -> 18 -> 3 -> 9. First jump forward (+3), then forward again (+15 to 18), then backward (-15 to 3), then forward (+6... wait, that's not allowed). Actually: 0 -> 3 -> 18 -> 3 -> 6 -> 9 (but 6 might be forbidden). The optimal path is 0 -> 3 -> 6 -> 9.
example_2.py โ Impossible case
$
Input:
forbidden = [8,3,16,6,12,20], a = 15, b = 13, x = 11
โบ
Output:
-1
๐ก Note:
It's impossible to reach position 11 with the given constraints. The bug cannot find a valid sequence of jumps to reach its home.
example_3.py โ Direct jump
$
Input:
forbidden = [1,6,2,14,5,17,4], a = 16, b = 9, x = 7
โบ
Output:
2
๐ก Note:
The bug can reach home in 2 jumps: 0 -> 16 -> 7. Jump forward by 16, then backward by 9 to reach position 7.
Constraints
- 1 โค forbidden.length โค 1000
- 1 โค a, b, forbidden[i] โค 2000
- 0 โค x โค 2000
- All the elements in forbidden are distinct
- Position x is not forbidden
Visualization
Tap to expand
Understanding the Visualization
1
Start the Journey
Bug starts at position 0, ready to jump forward or backward
2
Level 1 Exploration
Explore all positions reachable in exactly 1 jump
3
Level 2 Exploration
From each Level 1 position, explore all reachable positions in 1 more jump
4
Continue Until Home
Keep exploring level by level until the bug reaches its home
5
Shortest Path Found
The first time we reach home gives us the minimum number of jumps
Key Takeaway
๐ฏ Key Insight: BFS explores positions level by level, guaranteeing that the first time we reach the target, we've found the shortest path. The state includes both position and jump direction capability.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code