Leetcode greedy algorithm jump-game

Given an array of non-negative integers, you are initially at the first position of the array.

Each element in the array represents the maximum length you can jump at that position.

Determine if you can reach the last position.

Example 1:

Input: [2,3,1,1,4]
Output: true
Explanation: Jump 1 step from position 0 to 1, then jump 3 steps to the last position.
Example 2:

Input: [3,2,1,0,4]
Output: false
Explanation: No matter what, you will always reach the position at index 3. But the maximum jump length for that position is 0, so you can never get to the last position.

The idea I started with this question is that the given number is non-negative, so if there is 0, it is impossible to reach the end. This is not necessarily, if the value after 0 can also be reached, the latter value can also jump backward. And if there are multiple 0s in a row from the last digit, it is also possible to jump to the end.
This is incorrect code.

public boolean canJump(int[] A) {
        if (A.length == 1) {
            return true;
        }
        for (int i = 0; i < A.length; i++) {
            if (A[i] == 0) {
                return false;
            }
        }
        return true;
    }

Use the breadth-first search algorithm to do
this problem is similar to a point on the coordinate axis, there are several ways to move +1, -1, *2, to find the fewest steps to a certain point.

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

/**
 * Created by Administrator on 2018/5/7 0007.
 */
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(canJump(a));
        System.out.println(canJump(b));
    }

    public static boolean canJump(int[] A) {
        if (A == null || A.length == 0) {
            return false;
        }
        Queue<Node> queue = new LinkedList<>();
        int far = 0, nextFar = 0;
        queue.add(new Node(0, A[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 true;
            } 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]));
                    set.add(i);
                }
            }
            far = nextFar;
        }
        return false;
    }

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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325855205&siteId=291194637