leetcode 1306. Jump Game III(跳跃游戏 3)

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

给一个数组,从start的index出发,每次能左移或右移arr[start]个位置
问能不能走到值为0的index处

显然要用DFS或者BFS

用DFS要注意

  1. 要有visited数组,访问过的地方不要再重复访问,否则容易出现死循环
  2. 如果不修改原数组数值的情况下,需要另有一个数组记录访问过的位置是否能到达0,要么就改变原数组数值,记录visited。这样就避免了重复计算
  3. 注意index是否超出了数组边界,判断index是否<0或者>=arr.length

这里不改变原数组的值

    public boolean canReach(int[] arr, int start) {       
       if(arr == null || start < 0 || start >= arr.length) {
           return false;
       } 
        
       boolean[] bVisited = new boolean[arr.length];
       boolean[] bReach = new boolean[arr.length];
        
       return dfs(arr, start, bVisited, bReach);
    }
    
    boolean dfs(int[] arr, int start, boolean[] bVisited, boolean[] bReach) {
        if(start < 0 || start >= arr.length) return false;
        if(bVisited[start]) return bReach[start];
        bVisited[start] = true;
        if(arr[start] == 0) {
            bReach[start] = true;
            return true;
        }
        if(bReach[start]) return true;
        
        return dfs(arr, start - arr[start], bVisited, bReach) || dfs(arr, start + arr[start], bVisited, bReach);
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

蓝羽飞鸟

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值