JAVA Advanced
JAVA Advanced
Maneuvering a Cave:
A Robot wants to move through a cave grid of size MxN . (M- Rows N- Columns).It
starts from (0,0) and destination is (M-1,N-1). It can only move right or down .
Calculate the total number of ways robot can reach the destination
Consider you are at the start of array i.e.)0th index position. Every index will hold
the value of maximum steps you take from that index in one jump(if the value is 0
then person cannot move).
You have to reach the end of the array n-1(n >1). Print the minimum number of steps
required to reach the endpoint. If it’s not possible to reach the end print -1.
Question 3
Input Constraint:
1 <= n <= 1000
Input Format:
First line contains the n
Output Format:
Print the minimum number of steps or -1 if we cannot reach the end
Question 3
Sample Input: Sample Output:
5 2
24151
Explanation
From 0th index jump to 1st index and then jump to the 4th index.
1 import java.util.*;
2 public class MyClass {
3 public static void main(String args[]) {
4 Scanner sc= new Scanner(System.in);
5 int n =sc.nextInt();
6 int arr[]=new int[n];
7 for(int i=0;i<n;i++)
8 {
9 arr[i]=sc.nextInt();
10 }
11 int maxLevel = arr[0];
12 int step = arr[0];
13 int jump = 1;
14 if(arr[0] == 0)
15 {
16 jump=-1;
17 }
18
19
20
21
22
1 else
2 for(int i=1;i<n-1;i++)
3 {
4 maxLevel = Math.max(maxLevel,i+arr[i]);
5 step--;
6 if(step == 0)
7 {
8 jump++;
9 if(i>= maxLevel)
10 {
11 jump=-1;
12 break;
13 }
14 step=maxLevel-i;
15 }
16 }
17 System.out.print(jump);
18 }
19 }
20
21
22
Question 4
Perfect batch:
Write a java code to find if batches of size 3 are summing up to same value in the
given input.