题目描述:Given an array of non-negative integers, you are initially positioned at the first index of the array.Each element in the array represents your maximum jump length at that position.
Your goal is to reach the last index in the minimum number of jumps.
For example:
Given array A =[2,3,1,1,4]
The minimum number of jumps to reach the last index is2. (Jump1step from index 0 to 1, then 3 steps to the last index.)
题目描述:要求出达到数组末尾的最小跳数。
方法一:看到这个题目,最直观的想法就是用求无权最短路径,把数组的各元素看做图中的结点,计算最短路径。最短路径算法一般采用广度优先遍历方法——bfs。广度优先遍历借助队列实现。
import java.util.*;
public class Solution {
//可以使用最短路径算法,bfs,队列处理
public int jump(int[] A) {
if(A.length==0)
return -1;
if(A.length==1)
return 0;
//数组step[]表示到各个结点的最短路径
int[] step = new int[A.length];
//数组visited[]表示结点是否已经被访问过(是否已被添加到队列中)
boolean[] visited = new boolean[A.length];
LinkedList <Integer> queue = new LinkedList <>();
int i = 0;
queue.offer(i);
visited[i] = true;
while(!queue.isEmpty()) {
i = queue.poll();
for(int j=1;j<=A[i];++j) {
//此处必须判断结点是否已经被访问过,避免重复将结点添加到队列,以及最短路径结果偏大。
if(!visited[i+j]) {
step[i+j] = step[i] + 1;
queue.offer(i+j);
visited[i+j] = true;
}
if(i+j>=A.length-1)
return step[i+j];
}
}
return -1;
}
}
方法二:联想到另一个相关的jump game算法题,想着这个题目可以用类似的贪心算法实现,应该相对更加简单。
public int jump(int[] A) {
int cur = 0;//每个台阶内能到达的最远处
int last = 0;//每一步能直接跨越的最远距离
int step = 0;//步数
for(int i=0;(iA.length)(cur>=i);++i) {
if(i>last) {
last = cur;
step++;
}
cur = Math.max(cur,A[i]+i);
}
return step;
}