The Ninja had finished his last exam and wanted to reach home as soon as possible to play video games. His exam centre lies at position 0, and his home is at position ‘X’ on the x-axis. The ninja jumps according to the following rules:
You are given an array ‘RESTRICTED’ containing the restricted positions. You are also given three integers, ‘A’, ‘B’, and ‘X’. Your task is to find the minimum number of jumps needed for the ninja to reach his home. If there is no possible sequence of jumps that lands ninja on position ‘X’. return -1.
For Example:
You are given ‘RESTRICTED’ = {1, 3}, ‘A’ = 2, ‘B’ = 1 and ‘X’ = 4. Then ninjas requires two jumps(0 -> 2 -> 4) to reach his home.
The first line of the input contains a single integer 'T', representing the number of test cases.
The first line of each test case contains four space-separated integers, ‘A’, ‘B’, ‘X’, and ‘N’.
The Second line contains ‘N’ space-separated integers representing the restricted positions.
Output Format:
For each test case, print the minimum number of jumps needed for the ninja to reach his home.
Print the output of each test case in a separate line.
Note:
You do not need to print anything. It has already been taken care of. Just implement the given function.
1 <= T <= 10
1 <= N <= 1000
1 <= A, B, RESTRICTED[i] <= 2000
0 <= X <= 2000
RESTRICTED contains distinct elements.
Position X is not restricted.
Time Limit: 1 sec
2
2 1 4 2
1 3
3 1 3
1 2 7
2
3
For the second test case, the ninjas require two jumps(0 -> 2 -> 4) to reach his home.
For the second test case, the ninjas require three jumps(0 -> 3 -> 6 -> 5) to reach his home.
2
2 1 5 1
1
3 2 4
1 2 3 7
4
-1
Find the shortest path to home.
Prerequisite: Breadth-First Search
In this approach, we perform Breadth-First Search from position 0.
For each position:
We will add the next possible position to the BFS queue.
At each jump, we will increment the number of the moves.
The max jump is ((maximum value of ‘RESTRICTED’) + 2 * ‘B’). If we don’t set the max jump, we will keep on adding ‘A’ to the current position and jumping forward to infinity.
Algorithm :
O(A + B + MAX(X, MAX(RESTRICTED)), where 'A', 'B', and 'X' are the input integers and 'MAX'('RESTRICTED') is the maximum element of 'RESTRICTED' array.
The maximum number of jumps is A + B + MAX(X, MAX(RESTRICTED). Hence, the total time complexity is O(A + B + MAX(X, MAX(RESTRICTED)).
O(A + B + MAX(X, MAX(RESTRICTED)).
We may have to store a maximum of (A + B + MAX(X, MAX(RESTRICTED)) states in BFS queue. Hence, the total space complexity is O(A + B + MAX(X, MAX(RESTRICTED)).