# 题目

输入：
7 4
10 0 2 1 1 0 1

3


1<= N <= 10000
1 <= P <= N

# 思路

LeetCode的jump game II， 但他只能往后跳。

# 代码

package shen.leetcode.solution.toutiao;

public class Solution_toutiao_0630 {

public static void main(String[] args) {
System.out.println(core(new int[]{10, 0, 2, 1, 1, 0, 1}, 7));
}

public static int core(int arr[], int start) {
q.offer(new Node(start - 1, 0));
while (!q.isEmpty()) {
Node curNode = q.poll();
if (arr[curNode.index] == 0) {
continue;
}
int maxLength = arr[curNode.index];
if (curNode.index + maxLength > arr.length - 1) {// 大于长度,说明可以到达终点,返回
return curNode.step + 1;
}
if (curNode.index - maxLength >= 0) { // 可以往回跳
for (int i = curNode.index - maxLength; i <= curNode.index - maxLength + 2 * arr[curNode.index]; i++) {
if (i == curNode.index) continue;
q.offer(new Node(i, curNode.step + 1));
}
} else {
int begin = maxLength - curNode.index;
for (int i = begin; i <= begin + 2 * arr[curNode.index] - begin; i++) {
if (i == curNode.index) continue;
q.offer(new Node(i, curNode.step + 1));
}
}

}
return -1;
}

public static class Node {
int index;
int step;

public Node(int index, int step) {
this.index = index;
this.step = step;
}
}

}