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 

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

 

思路:

给定数组与开始点start,在位置i可以往前到arr[i]+i,或者退后到i-arr[i],返回能否走到arr中任意位置的0。按照提示我用了BFS做,看了大神们基本都是用单行DFS递归做。先讲一下BFS,用queue模拟,另外建一个数组来记录已经访问过的index。如果下一步可以走,即确认index合法,就放入queue,并且将当前index记录为访问过。如果当前对应值是0则可以返回true,否则就继续。如果可以访问的都访问完了,即queue的size为0了,跳出while并返回false。DFS的话思路差不多,也是用一个额外的hash set或者vector记录已经访问过的index,然后每一步递归都寻找前后可以走的位置即可。这里就不分开了,代码1是BFS,代码2是DFS,自己写的就不追求一行了。

 

代码1:

class Solution {
public:
    bool canReach(vector<int>& arr, int start) {
        int n=arr.size();
        vector<int> visited(n,0);
        queue<int> q;
        q.push(start);
        while(q.size())
        {
            int len=q.size();
            for(int i=0;i<len;i++)
            {
                int cur=q.front();
                q.pop();
                if(arr[cur]==0)
                    return true;
                if(cur+arr[cur]<n&&!visited[cur+arr[cur]])
                    q.push(cur+arr[cur]);
                if(cur-arr[cur]>=0&&!visited[cur-arr[cur]])
                    q.push(cur-arr[cur]);
                visited[cur]=1;
            }
        }
        return false;
    }
};

 

代码2:

class Solution {
public:
    bool canReach(vector<int>& arr, int start) {
        vector<int> visited(arr.size(),0);
        return dfs(arr,start,visited);
    }
private:
    bool dfs(vector<int>& arr, int start, vector<int>& visited)
    {
        if(start<0||start>=arr.size()||visited[start])
            return false;
        if(arr[start]==0)
            return true;
        visited[start]=1;
        return dfs(arr,start+arr[start],visited)||dfs(arr,start-arr[start],visited);
    }
};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值