题目
/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;}}
如果觉得《leetcode 1306. Jump Game III | 1306. 跳跃游戏 III(BFS)》对你有帮助,请点赞、收藏,并留下你的观点哦!