LeetCode 1654: Minimum Jumps to Reach Home Solution
Master LeetCode problem 1654 (Minimum Jumps to Reach Home), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
1654. Minimum Jumps to Reach Home
Problem Explanation
Explanation:
To solve this problem, we can use a breadth-first search (BFS) approach. We will start from position 0 and explore all possible valid moves the bug can make. We will keep track of the visited positions and the number of jumps required to reach each position. If the bug reaches the home position x, we return the number of jumps required. If it is not possible to reach x, we return -1.
Algorithm:
- Initialize a queue for BFS and a set to track visited positions.
- Perform BFS starting from position 0 with 0 jumps.
- At each step, consider two possible moves: a jump forward and a jump backward.
- Check if the new positions are valid and not in the forbidden set.
- If the bug reaches position x, return the number of jumps.
- If the queue is empty and x is not reached, return -1.
Time Complexity:
The time complexity of this algorithm is O(max(x, max(forbidden))).
Space Complexity:
The space complexity of this algorithm is O(max(x, max(forbidden))).
Solution Code
class Solution {
public int minimumJumps(int[] forbidden, int a, int b, int x) {
Set<Integer> visited = new HashSet<>();
Set<Integer> forbiddenSet = new HashSet<>();
for (int f : forbidden) {
forbiddenSet.add(f);
}
Queue<int[]> queue = new LinkedList<>();
queue.offer(new int[]{0, 0});
visited.add(0);
int maxPos = x + 2 * a + b;
while (!queue.isEmpty()) {
int[] current = queue.poll();
int pos = current[0];
int jumps = current[1];
if (pos == x) {
return jumps;
}
if (pos + a < maxPos && !forbiddenSet.contains(pos + a) && visited.add(pos + a)) {
queue.offer(new int[]{pos + a, jumps + 1});
}
if (pos - b >= 0 && pos - b != a && !forbiddenSet.contains(pos - b) && visited.add(pos - b)) {
queue.offer(new int[]{pos - b, jumps + 1});
}
}
return -1;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 1654 (Minimum Jumps to Reach Home)?
This page provides optimized solutions for LeetCode problem 1654 (Minimum Jumps to Reach Home) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 1654 (Minimum Jumps to Reach Home)?
The time complexity for LeetCode 1654 (Minimum Jumps to Reach Home) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 1654 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1654 in Java, C++, or Python.