1306. Jump Game I I I

1306. Jump Game III #

Problem #

Given an array of non-negative integers arr, you are initially positioned at start index of the array. When you are at index i, you can jump to i + arr[i] or i - arr[i], check if you can reach to any index with value 0.

Notice that you can not jump outside of the array at any time.

Example 1:

Input: arr = [4,2,3,0,3,1,2], start = 5
Output: true
Explanation: 
All possible ways to reach at index 3 with value 0 are: 
index 5 -> index 4 -> index 1 -> index 3 
index 5 -> index 6 -> index 4 -> index 1 -> index 3

Example 2:

Input: arr = [4,2,3,0,3,1,2], start = 0
Output: true 
Explanation: 
One possible way to reach at index 3 with value 0 is: 
index 0 -> index 4 -> index 1 -> index 3

Example 3:

Input: arr = [3,0,2,1,2], start = 2
Output: false
Explanation: There is no way to reach at index 1 with value 0.

Constraints:

  • 1 <= arr.length <= 5 * 10^4
  • 0 <= arr[i] < arr.length
  • 0 <= start < arr.length

Problem Summary #

Here is a non-negative integer array arr, and you are initially located at the starting index start of the array. When you are at index i, you can jump to i + arr[i] or i - arr[i]. Determine whether you can jump to any index whose corresponding element value is 0. Note that under no circumstances can you jump outside the array.

Constraints:

  • 1 <= arr.length <= 5 * 10^4
  • 0 <= arr[i] < arr.length
  • 0 <= start < arr.length

Solution Approach #

  • Given a non-negative array and a starting index start. Standing at start, each time you can jump to i + arr[i] or i - arr[i]. Determine whether you can jump to an index whose element value is 0.

  • This problem tests recursion. At each step, you need to check 3 possibilities:

    1. Whether the current position is a target point with element value 0.
    2. Jump forward by arr[start], and check whether you can stand on a target point with element value 0.
    3. Jump backward by arr[start], and check whether you can stand on a target point with element value 0.

    For the 2nd and 3rd possibilities, just use recursion. At each step, check whether any of these 3 possibilities can jump to an index whose element value is 0.

  • arr[start] += len(arr) This step is only to mark that this index has already been used; the next time it is checked, this index will be filtered out by the if condition.

Code #

func canReach(arr []int, start int) bool {
	if start >= 0 && start < len(arr) && arr[start] < len(arr) {
		jump := arr[start]
		arr[start] += len(arr)
		return jump == 0 || canReach(arr, start+jump) || canReach(arr, start-jump)
	}
	return false
}

Calendar Jun 25, 2026
Edit Edit this page
Total visits:   You are visitor No.
中文