Min Jumps Array

Given an array of non-negative integers, A, of length N, you are initially positioned at the first index of the array.

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

Return the minimum number of jumps required to reach the last index.

If it is not possible to reach the last index, return -1.

Input Format:

The first and the only argument contains an integer array, A.
Output Format:

Return an integer, representing the answer as described in the problem statement.
Constraints:

1 <= N <= 1e6
0 <= A[i] <= 50000
Examples:

Input 1:
    A = [2, 1, 1]

Output 1:
    1
    
Explanation 1:
    The shortest way to reach index 2 is
        Index 0 -> Index 2
    that requires only 1 jump.

Input 2:
    A = [2,3,1,1,4]

Output 2:
    2

Explanation 2:
    The shortest way to reach index 4 is
        Index 0 -> Index 1 -> Index 4
    that requires 2 jumps.

Method1:

Use BFS with queue

Solution 1:

Time: O(n)
Space: O(n)

public class Solution {
    public int jump(int[] A) {
        if (A == null || A.length == 0) return 0;
        Deque<Integer> queue = new ArrayDeque<>();
        queue.offer(0);
        int jump = 0;
        while (!queue.isEmpty()) {
            int size = queue.size();
            jump ++;
            for (int i = 0; i < size; i ++) {
                int curIndex = queue.poll();
                int val = A[curIndex];
                if (curIndex + val >= A.length - 1) {
                    return jump;
                }
                for (int j = 1; j <= val; j ++) {
                    queue.offer(curIndex + j);
                }
            }
        }
        return -1;
    }
}

Method 2:

BFS and greedy, only choose the next node that goes the furthest.

Solution 2:

public class Solution {
    public int jump(int[] A) {
        if (A == null || A.length <= 1) return 0;
        int curIndex = 0;
        int jump = 0;
        while (curIndex < A.length) {
            jump ++;
            int range = A[curIndex];
            if (curIndex + range >= A.length - 1) {
                return jump;
            }
            int nextRange = 0;
            int nextIndex = 0;
            for (int i = 1; i <= range; i ++) {
                if (curIndex + i + A[curIndex + i] > nextRange) {
                    nextRange = curIndex + i + A[curIndex + i];
                    nextIndex = curIndex + i;
                }
            }
            if (nextIndex <= curIndex) return -1;
            curIndex = nextIndex;
        }
        return -1;
    }
}