Minimum Jumps to Reach Home Problem
Description
LeetCode Problem 1654.
A certain bug's home is on the x-axis at position x. Help them get there from position 0.
The bug jumps according to the following rules:
- It can jump exactly
apositions forward (to the right). - It can jump exactly
bpositions backward (to the left). - It cannot jump backward twice in a row.
- It cannot jump to any
forbiddenpositions.
The bug may jump forward beyond its home, but it cannot jump to positions numbered with negative integers.
Given an array of integers forbidden, where forbidden[i] means that the bug cannot jump to the position forbidden[i], and integers a, b, and x, return the minimum number of jumps needed for the bug to reach its home. If there is no possible sequence of jumps that lands the bug on position x, return -1.
Example 1:
Input: forbidden = [14,4,18,1,15], a = 3, b = 15, x = 9
Output: 3
Explanation: 3 jumps forward (0 -> 3 -> 6 -> 9) will get the bug home.
Example 2:
Input: forbidden = [8,3,16,6,12,20], a = 15, b = 13, x = 11
Output: -1
Example 3:
Input: forbidden = [1,6,2,14,5,17,4], a = 16, b = 9, x = 7
Output: 2
Explanation: One jump forward (0 -> 16) then one jump backward (16 -> 7) will get the bug home.
Constraints:
1 <= forbidden.length <= 10001 <= a, b, forbidden[i] <= 20000 <= x <= 2000- All the elements in
forbiddenare distinct. - Position
xis not forbidden.
Solution
Approach: BFS
A state is the bug's position plus whether its last jump was backward (it may not jump backward twice in a row). BFS over these states gives the fewest jumps.
The only tricky part is how far right the bug ever needs to go. Positions, a, b and x are at most 2000, and one can show that a shortest path never needs to pass 6000, so positions are capped at 6000.
Start from (0, last jump forward). From a state at position i:
- jump forward to
i + a(the last jump is now forward); - if the last jump was forward, jump back to
i - b(the last jump is now backward).
A new state is kept only if its position is in [0, 6000), not forbidden, and not visited yet. Process the queue level by level; the level at which position x comes out is the answer. If the queue runs empty, return -1.
Complexity: O(M) time and space, where M = 6000 is the position bound.
from collections import deque
class Solution:
def minimumJumps(self, forbidden: List[int], a: int, b: int, x: int) -> int:
s = set(forbidden)
q = deque([(0, 1)])
vis = {(0, 1)}
ans = 0
while q:
for _ in range(len(q)):
i, k = q.popleft()
if i == x:
return ans
nxt = [(i + a, 1)]
if k & 1:
nxt.append((i - b, 0))
for j, k in nxt:
if 0 <= j < 6000 and j not in s and (j, k) not in vis:
q.append((j, k))
vis.add((j, k))
ans += 1
return -1