题目
一个数组代表跳板,数字代表向前或向后可以跳的最大距离(比如3,那么跳1,、2、3都行),0代表悬崖(跳上去摔死)。
指定一个出生点P,求到终点需要跳的最小次数(终点是最后一个元素后面),无法到达输出-1
。
输入:
第一行:数组长度N,出生点P
第二行:N个数字
输出:
最小次数
示例:
输入:
7 4
10 0 2 1 1 0 1
输出:
3
1<= N <= 10000
1 <= P <= N
思路
LeetCode的jump game II, 但他只能往后跳。
最小次数,那么就是BFS了,动手写代码
代码
用一个队列实现BFS。
package shen.leetcode.solution.toutiao;
import java.util.LinkedList;
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 LinkedList<Node> q = new LinkedList<>();
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;
}
}
}