【发布时间】:2020-10-13 04:22:22
【问题描述】:
我编写了这段代码来解决课堂上给我的问题,任务是使用回溯解决"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","R","R","E","L","L","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 recursion backtracking