问题描述
我已经编写了这段代码来解决课堂上给我的问题,任务是使用回溯来解决"toads and frogs problem"。我的代码解决了这个问题,但是一旦解决,它就不会停止(它会不断打印“状态”,显示不是解决问题的其他路径),有没有办法做到这一点?这是代码:
def solution_recursive(frogs):
#Prints the state of the problem (example: "L L L L _ R R R R" in the starting case
#when all the "left" frogs are on the left side and all the "right" frogs are on
#the right side)
show_frogs(frogs)
#If the solution is found,return the list of frogs that contains the right order
if frogs == ["R","R","E","L","L"]:
return(frogs)
#If the solution isn't the actual state,then start (or continue) recursion
else:
#S_prime contains possible solutions to the problem a.k.a. "moves"
S_prime = possible_movements(frogs)
#while S_prime contains solutions,do the following
while len(S_prime) > 0:
s = S_prime[0]
S_prime.pop(0)
#Start again with solution s
solution_recursive(s)
谢谢!
解决方法
找到答案后,如何停止回溯算法?
您可以将Python exception facilities用于此目的。
您还可以采用以下约定:solution_recursive
返回一个布尔值告诉停止回溯。
这也是一个品味或见解的问题。
,我想扩展一下您的递归代码。
您的问题之一是您的程序显示的路径不是解决方案。这是因为每次对solution_recursive
的调用都以
show_frogs(frogs)
无论frogs
是否是解决方案。
然后,您说即使找到了解决方案,程序仍在继续。造成这种情况的原因有两个,第一个是您的while循环不关心是否已找到解决方案,它将经历所有可能的移动:
while len(S_prime) > 0:
另一个原因是每次调用此函数时都要重新初始化S_prime
。我真的很惊讶,它并没有进入无限循环,只是检查了一次又一次的第一步。
由于这是课堂上的问题,我不会为您提供确切的解决方案,但是这些问题需要解决,并且我相信您的教材可以为您提供指导。