Ninja bought a plane that can cover a distance of at most ‘K’ units in one flight. Now, the ninja wants to show this plane to his best friend, whose house lies at point (X, 0) on the x-axis. There are multiple airports on the x-axis marked by 1. If there is no airport at any point, then it is marked as 0.
Given an integer array ‘AIRPORTS’ of size ‘N’ containing the information about airports on the x-axis, can you find the minimum number of stops that must be taken by the plane to reach the destination (X,0) on the x-axis. If the destination is unreachable, return -1. The plane starts from the origin (0, 0).
For example:You are given AIRPORTS = [1, 1, 1, 0, 1, 0], ‘K’ = 2 and ‘X’ = 4.
The answer will be 1. The plane makes its first stop at (2, 0) and then reaches the destination (4, 0) in the next fight. Hence the total number of stops is 1.
The first line contains an integer 'T' which denotes the number of test cases.
The first line of each test case contains three space-separated integers, ‘N’, ‘K’, ’X’, representing the length of the ‘AIRPORTS’ array, maximum distance covered by plane in one flight, and destination on the x-axis, respectively.
The second line of each test case contains N space-separated integers, representing the information about the airports on the x-axis.
Output Format:
For each test case, print a single integer, denoting the minimum number of stops that must be taken by the plane to reach the destination (X,0) on the x-axis.
The output of each test case will be printed in a separate line.
1 <= T <= 10
1 <= N <= 5000
1 <= K < N
1 <= X < N
0 <= AIRPORTS[i] <= 1
Time limit: 1 sec
Note:
You do not need to input or print anything, as it has already been taken care of. Just implement the given function.
2
6 2 4
1 1 1 0 1 0
4 3 3
1 0 1 1
1
0
For the first test case, the answer will be 1. The plane makes its first stop at (2, 0) and then reaches the destination (4, 0) in the next fight. Hence the total number of stops is 1.
For the second test case, the answer will be 0. The plane can directly reach the destination without making any stop. Hence the total number of stops is 0.
2
4 2 3
1 0 0 1
5 3 2
1 0 1 0 0
-1
0
Find the shortest path to the destination
In this approach, we will find the shortest path to the destination using Breadth-First Search. The starting point will be the origin, and all the airports at a distance at most ‘K’ from any airport ‘A’ will be considered the neighbors of ‘A’.
Algorithm:
O(N * K), where N is the size of the input array ‘AIRPORTS’ and ‘K’ is the given integer.
Every element of the input array will be added to the ‘Q’ only once’, for every element in the ‘Q’ we will check the next ‘K’ points. Hence the overall time complexity is O(N * K).
O(N).
The size of queue ‘Q’ and boolean array ‘VISITED’ will be at most ‘N’. Hence the overall space complexity is O(N).