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;
        }
    }
    
  • 相关阅读:
    什么是C/S和B/S结构(二)转
    程序员的爱情独白(转)
    为什么美女喜欢软件开发的gg做老公
    C# DataGridView中 显示行号
    联想F31笔记本配置分析
    理解.NET中的数据库连接池[转]
    C#获取当前路径的方法集合
    vb6,vs2005快捷键使用,提高操作速度[转]
    Visual Studio Team System 2008 Team Suite (VSTS 2008) 简体中文正式版下载(正在下载中 60K/秒)
    一个正在项目中使用的DataInterface数据访问接口
  • 原文地址:https://www.cnblogs.com/mapoos/p/14058603.html
Copyright © 2011-2022 走看看