zoukankan      html  css  js  c++  java
  • 1306. Jump Game III

    package LeetCode_1306
    
    import java.util.*
    
    /**
     * 1306. Jump Game III
     * https://leetcode.com/problems/jump-game-iii/description/
     * 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 {
        //try bfs
        fun canReach(arr: IntArray, start: Int): Boolean {
            if (arr == null || arr.size == 0) {
                return false
            }
            val N = arr.size
            val visited = BooleanArray(N)
            val queue = LinkedList<Int>()
            queue.add(start)
            visited[start] = true
            while (queue.isNotEmpty()) {
                val currentInt = queue.poll()
                if (arr[currentInt] == 0) {
                    return true
                }
                //do some expand
                val needAddIndex = currentInt - arr[currentInt]
                val needAddIndex2 = currentInt + arr[currentInt]
                if (needAddIndex >= 0 && !visited[needAddIndex]) {
                    visited[needAddIndex] = true
                    queue.add(needAddIndex)
                }
                if (needAddIndex2 < N && !visited[needAddIndex2]) {
                    visited[needAddIndex2] = true
                    queue.add(needAddIndex2)
                }
            }
            return false
        }
    }
  • 相关阅读:
    Linux搭建iscsi服务,客户端(Linux&Win XP)挂载使用
    SecucreCRT安装与破解
    最全的HCIA-R&S实验笔记
    AtCoder Grand Contest 036
    Comet OJ CCPC-Wannafly & Comet OJ 夏季欢乐赛(2019)
    2019慈溪集训小记
    Codeforces Round #573 (Div. 1)
    Comet OJ
    Codeforces Round #576 (Div. 1)
    Codechef August Challenge 2019 Division 2
  • 原文地址:https://www.cnblogs.com/johnnyzhao/p/12722357.html
Copyright © 2011-2022 走看看