需要使用两把枪 A 和 B 来杀死一个怪物(有 N 个头)。当使用枪A时,它会砍6个头,但如果怪物没有死(头数> 0),它会长出3个头。当使用枪 B 时,它会砍掉 4 个头,但如果怪物没有死,它会长出 2 个头。如果 N<(枪可以切割的头数),在这种情况下,枪不能使用。如果 N=-1,怪物和猎人都会死。
问题需要找出是否有可能杀死怪物,猎人是否在试图杀死怪物时死亡以及最短的路径。
我编写了以下 Python 程序来解决上述问题:
def A(heads, path):
if heads < -1:
path = []
return "Impossible to kill"
heads -= 6
path.append("A")
if heads == 0:
print path
path = []
return "Monster dies"
if heads == -1:
return "Both monster and human die"
heads += 3
if A(heads, path)=="Monster dies" or B(heads, path) == "Monster dies":
return "Monster dies"
def B(heads, path):
if heads < -1:
path = []
return "Impossible to kill"
#print "B", path, heads
heads -= 4
path.append("B")
if heads == 0:
print path
path =[]
return "Monster dies"
if heads == -1:
return "Both monster and human die"
heads += 2
if A(heads, path)=="Monster dies" or B(heads, path) == "Monster dies":
return "Monster dies"
print A(10, [])
样本数据(问题提供):N=10时,最短路径为AAB。
我在程序中哪里出错了,解决这个问题的更好方法是什么?