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

x33g5p2x  于2021-12-30 转载在 其他  
字(0.6k)|赞(0)|评价(0)|浏览(252)

题目

https://leetcode.com/problems/jump-game-iii/

题解

正如 hint 所说:

用 BFS,跳过的就不跳了,直到全部跳过,即 count == arr.length, 则返回 fasle.
过程中,如果遇到 arr[i] == 0,则返回 true.

class Solution {
    public boolean canReach(int[] arr, int start) {
        boolean[] visited = new boolean[arr.length];
        int count = 0;
        Stack<Integer> stack = new Stack<>(); // BFS,存下标
        stack.push(start);
        while (count < arr.length && !stack.isEmpty()) {
            Stack<Integer> curStack = new Stack<>();
            while (!stack.isEmpty()) {
                Integer p = stack.pop();
                if (p >= 0 && p < arr.length && !visited[p]) {
                   if (arr[p] == 0) return true;
                    visited[p] = true;
                    count++;
                    curStack.push(p - arr[p]);
                    curStack.push(p + arr[p]);
                }
            }
            stack = curStack;
        }
        return false;
    }
}

相关文章