HackerRank Java- 1D Array (Part 2)




Given leap and game, complete the function in the editor below so that it returns true if you can win the game (or false if you cannot).



  1. import java.util.*;
  2. public class Solution {
  3. public static boolean canWin(int leap, int[] game, int i) {
  4. if (i < 0 || game[i] == 1)
  5. return false;
  6. if (i + 1 >= game.length || i + leap >= game.length)
  7. return true;
  8. game[i] = 1; //flag
  9. return canWin(leap, game, i + leap)
  10. || canWin(leap, game, i + 1)
  11. || canWin(leap, game, i - 1);
  12. }
  13. public static void main(String[] args) {
  14. Scanner scan = new Scanner(System.in);
  15. int q = scan.nextInt();
  16. while (q-- > 0) {
  17. int n = scan.nextInt();
  18. int leap = scan.nextInt();
  19. int[] game = new int[n];
  20. for (int i = 0; i < n; i++) {
  21. game[i] = scan.nextInt();
  22. }
  23. System.out.println((canWin(leap, game, 0)) ? "YES" : "NO");
  24. }
  25. scan.close();
  26. }
  27. }




codesadda.com

Codesadda.com is your home of programming solutions, tutorials, video tutorials and much more. Sign Up for our weekly newsletter to get update about new content.

Like us on Facebook | Connect with us on LinkedIn | Subscribe our Channel on Youtube