1306. Jump Game III (M)

Jump Game III (M)

題目

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.java

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

Example 1:ide

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:code

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:it

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

題意

從數組arr的指定位置開始,每次能向左跳或向右跳arr[i]個位置,問可否到達值爲0的位置。io

思路

直接DFS。若是當前位置的值爲0,則直接返回true;不然向兩個位置遞歸處理,注意要先判斷左右兩個下一跳的位置是否合法,且對應下標是否已訪問。class


代碼實現

Java

class Solution {
    public boolean canReach(int[] arr, int start) {
        return dfs(arr, start, new boolean[arr.length]);
    }

    private boolean dfs(int[] arr, int index, boolean[] visited) {
        if (arr[index] == 0) {
            return true;
        }

        int left = index - arr[index];
        int right = index + arr[index];
        boolean dfsLeft = false;
        boolean dfsRight = false;

        visited[index] = true;

        if (0 <= left && left < arr.length && !visited[left]) {
            dfsLeft = dfs(arr, left, visited);
        }
        if (0 <= right && right < arr.length && !visited[right]) {
            dfsRight = dfs(arr, right, visited);
        }

        return dfsLeft || dfsRight;
    }
}
相關文章
相關標籤/搜索