我正在写一个程序,找出一个游戏是可解还是不可解。
游戏规则是:
你从最左边开始
可以根据位置处数组的值向左或向右跳,并且不能超出端点例:a={4,4,1,5,2,6,3,4,2,0}你从最左边的位置开始,这样你就可以从4个地方跳到2(左边不可能)
我要检查我们是否能到达另一端,它总是等于0。
如果我们能到达最右边(即0),那么它是可解的,否则就不可解
我试过在python中使用递归,但不知道如何继续。
def KAuhop(b,c,d,current_position):
position_move=b[current_position]
if b[current_position+position_move]==0:
print("found")
else:
KAuhop(b,current_position+position_move,d,current_position)
print("Not found")
a=[4,4,1,5,2,6,3,4,2,0]
print(KAuhop(a,0,len(a)-1,0))
最佳答案
如果它可以跳转左或右的位置,那么请注意当程序结束或退出时,它将变成无限循环从一个位置跳到另一个位置。
请使用递归函数找到以下仅用于右跳转的解决方案。
lis=[4,4,1,5,2,4,3,4,2,0]
last_pos=len(lis)-1
pos = 0+lis[0]
def kauhop(lis,pos):
if (pos==last_pos):
print("found")
exit;
else:
new_pos = pos+lis[pos]
if(new_pos <= last_pos):
kauhop(lis,new_pos)
else:
print("Not found")
kauhop(lis,pos)
关于python - Python通过向左或向右跳检查是否有可能到达数组的最右端,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/47118379/