Minimum Jumps to Reach Home
Find the fewest forward and backward jumps that take a bug from position 0 to its home at x.
A bug starts at position 0 on a number line and wants to get home, to position xabforbiddenxx
Example 1
Output: 3
Explanation: 0 → 3 → 6 → 9.
Example 2
Output: -1
Example 3
Output: 2
Explanation: 0 → 16 → 7. Going past x and coming back is allowed.
The Idea
Think of a row of stepping stones numbered 0, 1, 2 and so on, with some of them cracked. The bug stands on stone 0, and its home is stone xab
In Example 1 the forward hop is 3, so the bug goes 0, 3, 6, 9 and is home after three jumps, without touching the forbidden stones 1, 4, 14, 15 and 18. Example 3 is less direct. Home is 7, the forward jump is 16, and stones 1, 2, 4, 5 and 6 are forbidden. A backward jump from 0 would land on -9, below 0. The only way home is to overshoot: forward to 16, then back 9 to 7.
So a route may wander past home and come back, and the number of possible routes grows with every jump. How can we be sure a route is the shortest one, without trying them all?
Count in rounds. List every stone the bug can stand on after one jump, then every stone after two jumps, and so on. The first round that contains x
After jump 1 the bug can only be on stone 16, since the backward jump from 0 is ruled out. Jump 2 offers two stones: forward again to 32, past home, or backward 9 to 7. Stone 7 is home, so the answer is 2, and round 1 had no way to be home.
This round-by-round search is called breadth-first search, or BFS for short: it looks at everything one jump away before anything two jumps away. Whenever every step costs the same, as every jump does here, it finds the fewest steps.
Solution Approach
Turning that idea into code means settling three things: how to keep the rounds in order, what to remember about each stone, and how far to the right the search may go.
Searching round by round
Why not simply try every sequence of jumps? Each jump has up to two choices, so there can be 2k sequences of k jumps: over 1,000 for ten jumps and over a million for twenty. Many of them end on the same stones, so most of that work is repeated.
Breadth-first search uses a queue instead, a line where new entries join at the back and are taken from the front. The queue starts with stone 0. The search takes an entry from the front and adds the stones its two jumps reach to the back. Because stones join behind the current round, every stone of round 2 is taken before any stone of round 3.
To know when a round ends, the search notes how many entries the queue holds when the round begins and takes exactly that many. Everything added meanwhile belongs to the next round.
What to remember about each stone
When can the search skip a stone it has reached before? Normally at once, because the earlier visit came in the same round or an earlier one. The rule about backward jumps makes it less simple. A bug that arrived on a stone by a backward jump cannot jump backward next, while one that arrived by a forward jump can. The same stone offers different moves depending on how the bug got there.
So the search treats each stone as two places: the stone reached by a forward jump, and the stone reached by a backward jump. Each of these is called a state. The search marks each state when it first reaches it and adds every state to the queue at most once. Keeping only one mark per stone would throw away the forward arrival whenever the backward arrival came first, and with it the backward jump that only the forward arrival may take.
How far to the right to search
Where should the search stop? Backward jumps cannot go below 0, but forward jumps have no end. If home cannot be reached, a search without a right edge would keep jumping right forever.
The edge used here, called limitxa + ba + blimit
Java Solution
The method minimumJumps
- First, put the forbidden positions into
, ablocked , so checking a stone takes one step. The same loop findsHashSet , the largest offurthest and the forbidden positions.x - Set
tolimit . Then createfurthest + a + b , avisited array with a row for every stone from 0 toboolean and two columns: column 0 marks the stone as reached forward, column 1 as reached backward.limit - Create
, anqueue (Java's array-based queue) of two-number entries: the position, then 1 if the bug got there by a backward jump and 0 otherwise. Start it withArrayDeque and mark{0, 0} .visited[0][0] - Run the rounds with two loops, one inside the other. The outer loop counts
, the round number. The inner loop takesjumps entries, as many as the queue held when the round began. For each entrysize , if its positionstate ispos , returnx .jumps - Try the forward jump to
. If it is at mostforward = pos + a , not inlimit and not yet reached forward, mark it and add it to the queue with a 0.blocked - Try the backward jump to
, but only ifback = pos - b is 0, meaning the bug did not just jump back. Ifstate[1] is at least 0, not inback and not yet reached backward, mark it and add it with a 1.blocked - If the queue runs empty, no round reached
, so return -1.x
The maina = 6b = 1x = 26
import java.util.ArrayDeque;
import java.util.HashSet;
import java.util.Queue;
import java.util.Set;
public class MinimumJumpsToReachHome {
public static int minimumJumps(int[] forbidden, int a, int b, int x) {
Set<Integer> blocked = new HashSet<>();
int furthest = x;
for (int f : forbidden) {
blocked.add(f);
furthest = Math.max(furthest, f);
}
int limit = furthest + a + b; // going further right never helps
// visited[pos][0]: reached by a forward jump, visited[pos][1]: by a backward jump
boolean[][] visited = new boolean[limit + 1][2];
Queue<int[]> queue = new ArrayDeque<>(); // each entry: {position, cameBack}
queue.add(new int[] {0, 0});
visited[0][0] = true;
for (int jumps = 0; !queue.isEmpty(); jumps++) {
for (int size = queue.size(); size > 0; size--) { // one round of jumps
int[] state = queue.poll();
int pos = state[0];
if (pos == x) {
return jumps;
}
int forward = pos + a;
if (forward <= limit && !blocked.contains(forward) && !visited[forward][0]) {
visited[forward][0] = true;
queue.add(new int[] {forward, 0});
}
int back = pos - b;
if (state[1] == 0 && back >= 0 && !blocked.contains(back) && !visited[back][1]) {
visited[back][1] = true; // no second backward jump from here
queue.add(new int[] {back, 1});
}
}
}
return -1;
}
public static void main(String[] args) {
System.out.println(minimumJumps(new int[] {14, 4, 18, 1, 15}, 3, 15, 9));
System.out.println(minimumJumps(new int[] {8, 3, 16, 6, 12, 20}, 15, 13, 11));
System.out.println(minimumJumps(new int[] {1, 6, 2, 14, 5, 17, 4}, 16, 9, 7));
System.out.println(minimumJumps(new int[] {5}, 2, 1, 0));
System.out.println(minimumJumps(new int[] {}, 6, 1, 26));
}
}
Running it prints:
3
-1
2
0
9
The 3, -1 and 2 at the top match the three examples. For Example 2 the queue ran empty before any round reached 11, so the method fell through to -1. The 0 in the fourth line is a home at the start: the first entry taken from the queue is already at x
Look at the last line, 9. The route is 0, 6, 5, 11, 10, 16, 15, 21, 20, 26: forward and backward in turn, ending with a forward jump. A version with one mark per stone returns -1 for the same input. There, stone 11 is first reached backward, from 12, and the forward arrival from 5 is thrown away, though only it may jump back to 10.
Complexity
The search handles each state at most once, and there are two states for every stone from 0 to limit
- Time: O(L + F), where L is
and F the number of forbidden positions. Buildinglimit takes F steps, and each of the 2(L + 1) states is added to the queue and taken from it at most once, with a fixed amount of work each time.blocked - Space: O(L + F). The
array has 2(L + 1) marks, the queue never holds more states than that, andvisited stores F positions.blocked
Breadth-first search over states rather than plain positions also solves