Loading

【leetcode】1306. Jump Game III

    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 
class Solution {
public:
    bool canReach(vector<int>& arr, int start) {
        //递归 如果返回true需要短路其他的递归
        //不能返回去再去查找以前的位置
        int len=arr.size();
        vector<int>dp(len,0); //标记矩阵
        return digui(arr,dp,start,len);
        
    }
    bool digui(vector<int>& arr,vector<int>& dp,int index,int len){
        
        if(index<0 || index>=len) return false;
        if(arr[index]==0) return true;
        if(dp[index]==1) return false;
        dp[index]=1;
        return digui(arr,dp,index-arr[index],len) || digui(arr,dp,index+arr[index],len);
    }
};
posted @ 2021-12-09 18:05  aalanwyr  阅读(40)  评论(0编辑  收藏  举报