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 is 2
. (Jump 1
step from index 0 to 1, then 3
steps to the last index.)
和上个题一样,不过这个题要求出达到目的所用的最小步骤
思路:BFS,根据例子来说,首先我们获得根节点 0:2,所以我们第一步可以到达的下一层的节点为1:3,2:1,第二部可以到达第三层的节点为
2:1,3:1,4:4,即可以到达最后一个节点,在具体操作中我们只需要保存每一层的开始和结束时候的节点即可
1 class Solution(object): 2 def jump(self, nums): 3 n,start,end,step = len(nums),0,0,0 4 while end < n-1: 5 step += 1 6 maxend = end+1 7 for i in range(start,end+1): 8 if i + nums[i] >= n-1: 9 return step 10 maxend = max(maxend,i+nums[i]) 11 start,end = end,maxend 12 return step 13