LeetCode 第 5297 题:跳跃游戏 III( 广度优先遍历)

竞赛页地址:https://leetcode-cn.com/contest/weekly-contest-169/problems/jump-game-iii/

思路:

1、模拟题目中描述的过程;

2、每个索引位置只用考虑一次,因为只能向左走或者向右走;这个过程可以用一棵二叉树描述。因此,使用广度优先遍历或者深度优先遍历均可,这里使用广度优先遍历,借助一个队列;

3、使用 visited 数组记录访问过的索引,这一点是很自然的;

4、在索引元素入队的时候,直接判断这个索引上的值是不是 0 0

5、如果回到一个已经访问过的索引,说明一定会循环下去(一直找不到 0 0 ),因此只需要关心没有访问过的索引。

Java 代码:

import java.util.LinkedList;
import java.util.Queue;

public class Solution {

    public boolean canReach(int[] arr, int start) {
        if (arr[start] == 0) {
            return true;
        }

        int len = arr.length;
        boolean[] visited = new boolean[len];

        Queue<Integer> queue = new LinkedList<>();
        queue.offer(start);
        visited[start] = true;

        while (!queue.isEmpty()) {
            Integer top = queue.poll();

            int right = top + arr[top];
            int left = top - arr[top];

            if (right < len && !visited[right]) {
                visited[right] = true;
                queue.offer(right);
                if (arr[right] == 0) {
                    return true;
                }
            }

            if (left >= 0 && !visited[left]) {
                visited[left] = true;
                queue.offer(left);
                if (arr[left] == 0) {
                    return true;
                }
            }
        }
        return false;
    }
}
发布了442 篇原创文章 · 获赞 330 · 访问量 123万+

猜你喜欢

转载自blog.csdn.net/lw_power/article/details/103752471