kangaroo crossing the river python

A kangaroo wants to jump from one side of the river to the other side of the river. The river is very wide, but there are many stakes in the middle of the river, one every one meter, and there is a spring on each stake. The kangaroo can jump on the spring. farther. The strength of each spring is different, and a number represents its strength. If the spring strength is 5, it means that the kangaroo can jump up to 5 meters in the next jump. If it is 0, it will get stuck and cannot continue to jump. The river is N meters wide. The initial position of the kangaroo is on the first spring. After jumping to the last spring, the river is crossed. Given the force of each spring, find the minimum number of jumps the kangaroo needs to reach the opposite bank. If the output cannot be reached -1 Input description: The input is divided into two lines, the first line is the array length N (1 ≤ N ≤ 10000), the second line is the value of each item, separated by spaces. Output description: Output minimum hop count, unable to reach output -1 Example 1 Input 5 2 0 1 1 1 Output 4

#递归方法
lens=int(input())
lists=list(map(int,input().split()))
ind_get={}
for i in range(1,lens+1):
    ind_get[i]=list(range(i+1,i+lists[i-1]+1))
def get_min(ind_get,ind):
    get_list=[]
    if ind==1:
        return 1
    for k, v in ind_get.items():
        if k < ind and ind in v:
            get_list.append(get_min(ind_get, k))
    min_num=min(get_list)
    return min_num+1
res=get_min(ind_get,lens)
print(res)
#动态规划
lens=int(input())
lists=list(map(int,input().split()))
dp=[i for i in range(lens+1)]
for i in range(lens+1):
    if i ==0:
        continue
    flag=False
    for j in range(i):
        if j+lists[j] >= i:
            dp[i]=min(dp[i],dp[j]+1)
            flag=True
    if flag==False:
        break
if flag==True:
    print(dp[lens])
else:
    print("-1")

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325861420&siteId=291194637