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

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

题目

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

题解

正如 hint 所说:

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

  1. class Solution {
  2. public boolean canReach(int[] arr, int start) {
  3. boolean[] visited = new boolean[arr.length];
  4. int count = 0;
  5. Stack<Integer> stack = new Stack<>(); // BFS,存下标
  6. stack.push(start);
  7. while (count < arr.length && !stack.isEmpty()) {
  8. Stack<Integer> curStack = new Stack<>();
  9. while (!stack.isEmpty()) {
  10. Integer p = stack.pop();
  11. if (p >= 0 && p < arr.length && !visited[p]) {
  12. if (arr[p] == 0) return true;
  13. visited[p] = true;
  14. count++;
  15. curStack.push(p - arr[p]);
  16. curStack.push(p + arr[p]);
  17. }
  18. }
  19. stack = curStack;
  20. }
  21. return false;
  22. }
  23. }

相关文章