In this HackerRank Java 1D Array (Part 2) problem you can move from index I to index i+1, i-1, or i+leap as long as the destination index is a cell containing a 0. if the destination index is greater than n-1, you win the game. we need to complete the canWin function and print true if the game can be won, otherwise false.

HackerRank Java 1D Array (Part 2) problem solution

HackerRank Java 1D Array (Part 2) problem solution

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {

    static int m, n;
          static  int arr[] = new int[200];
        static int pos[] = new int[200];
    
    public static void main(String[] args) {
        int t, i;

        
        Scanner sc = new Scanner(System.in);
        t = sc.nextInt();
        while(t-- >0)
        {
            n = sc.nextInt();
            m = sc.nextInt();
            
            for(i=0; i<n; i++)
                arr[i] = sc.nextInt();
            
            for(i=0; i<n; i++)
                pos[i] = 0;
            
            if(foo(0))
                System.out.println("YES");
            else
                System.out.println("NO");
                
        }
    }
    
    public static boolean foo(int index)
    {        
        boolean result = false;
        
        if(index+1 >= n || index + m >= n)
            return true;
        
        if(arr[index+1] == 0 && pos[index+1]==0)
            {
            pos[index+1]=1;
            result |= foo(index+1);                        
        }
        if(arr[index+m] == 0 && pos[index+m]==0) 
            {
            pos[index+m]=1;
            result |= foo(index+m);                
        }
        if(index>0 && arr[index-1]==0 && pos[index-1]==0)        
            {
            pos[index-1]=1;
            result |= foo(index-1);
        }   
        return result;
        
    }
    
}