logo CodeStepByStep logo

canJump

Language/Type: Java recursion backtracking string array

Write a recursive method named canJump that takes an array of integers as a parameter and returns true if a player could get from the first index of the array to the last index by playing a "jumping" game described as follows. The game begins with the player positioned at index 0. The goal is to reach the last index of the array, length-1, by "jumping" left or right repeatedly. The distance the player is allowed to jump is equal to the value stored in the array at the player's current index. If the player is at index 3 and index 3 stores the value 2, the player can jump to index 1 or 5.

For example, if the array is {3, 1, 2, 2, 5}, the player can reach the last index by jumping right 3, then left 2, then right 1, then right 2. If there is no way to reach the final index, return false.

You may assume that the array's elements are non-negative, but they could be 0. For an empty or one-element array, you should return true.

Constraints: Do not use any loops; you must use recursion. Do not declare any global variables. You can declare as many primitive variables like ints as you like. You are allowed to define other "helper" methods if you like; they are subject to these same constraints.

Method: Write a Java method as described, not a complete program or class.

You must log in before you can solve this problem.

Log In

Need help?

Stuck on an exercise? Contact your TA or instructor.

If something seems wrong with our site, please

Is there a problem? Contact us.