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;
}
}
版权说明 : 本文为转载文章, 版权归原作者所有 版权申明
原文链接 : https://blog.csdn.net/sinat_42483341/article/details/121809190
内容来源于网络,如有侵权,请联系作者删除!