zoukankan      html  css  js  c++  java
  • 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.

    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

    题意

    从数组arr的指定位置开始,每次能向左跳或向右跳arr[i]个位置,问能否到达值为0的位置。

    思路

    直接DFS。如果当前位置的值为0,则直接返回true;否则向两个位置递归处理,注意要先判断左右两个下一跳的位置是否合法,且对应下标是否已访问。


    代码实现

    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;
        }
    }
    
  • 相关阅读:
    悲观锁、乐观锁、行级锁、表级锁
    MySQL中锁详解(行锁、表锁、页锁、悲观锁、乐观锁等)
    刷题-力扣-148. 排序链表
    刷题-力扣-206. 反转链表
    刷题-力扣-203. 移除链表元素
    刷题-力扣-474. 一和零
    刷题-力扣-494. 目标和
    刷题-力扣-160. 相交链表
    刷题-力扣-34. 在排序数组中查找元素的第一个和最后一个位置
    刷题-力扣-33. 搜索旋转排序数组
  • 原文地址:https://www.cnblogs.com/mapoos/p/14058603.html
Copyright © 2011-2022 走看看