モンスター(N頭)を倒すには、2丁の銃AとBを使用する必要があります。銃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です。
プログラムのどこで間違ったのですか?この問題を解決するためのより良い方法は何ですか?