LeetCode 贪心算法 jump-game-ii 跳跃游戏 II

给定一个非负整数数组,你最初位于数组的第一个位置。

数组中的每个元素代表你在该位置可以跳跃的最大长度。

你的目标是使用最少的跳跃次数到达数组的最后一个位置。

示例:

输入: [2,3,1,1,4]
输出: 2
解释: 跳到最后一个位置的最小跳跃数是 2。
     从下标为 0 跳到下标为 1 的位置,跳 1 步,然后跳 3 步到达数组的最后一个位置。

在jump-game的基础上改动下,还是用的广度优先搜索

public class Solution {
    public static void main(String[] args) {
        int[] a = { 2,3,1,1,4};
        int[] b = {3,2,1,0,4};
        System.out.println(jump(a));
        System.out.println(jump(b));
    }

    public static int jump(int[] A) {
        if (A == null || A.length == 0 || A.length == 1) {
            return 0;
        }
        Queue<Node> queue = new LinkedList<>();
        int far = 0, nextFar = 0;
        queue.add(new Node(0, A[0], 0));
        HashSet<Integer> set = new HashSet<>();
        set.add(0);
        while (queue.size() > 0) {
            Node node = queue.poll();
            if (node.index + node.value >= A.length -1) {
                return node.times + 1;
            } else {
                nextFar = nextFar < node.index + node.value? node.index + node.value : nextFar;
            }
            for (int i = far; i <= nextFar; i++) {
                if (!set.contains(i)) {
                    queue.add(new Node(i, A[i], node.times+1));
                    set.add(i);
                }
            }
            far = nextFar;
        }
        return -1;
    }

    public static class Node {
        int index;
        int value;
        int times;
        public Node(int index, int value, int times) {
            this.index = index;
            this.value = value;
            this.times = times;
        }
    }

}

猜你喜欢

转载自blog.csdn.net/qq_31617121/article/details/80231509