我有一个递归函数,它的参数是数组,它存储了从(0,0)到(x,y)的路径,我不得不跳过一些定义为“不可用”的点
我是这样实现我的功能的
unAvailablePoint = [(1, 2), (3, 0), (0, 3), (2, 3), (0, 1)]
def steppable(point):
return point not in unAvailablePoint
def travel(x, y, path, visited):
if x >= 0 and y >= 0 and steppable((x, y)):
if (x, y) in visited:
return visited[(x, y)]
success = False
if (x, y) == (0, 0) or travel(x-1, y, path, visited) or travel(x, y-1, path, visited):
path = path + [(x, y)] #the path will remain empty even after the recursive call have done some changes to the path
success = True
visited[(x, y)] = success
return success
return False
path = []
visited = {}
travel(3, 3, path, visited)
print(path) //[]
当我最后打印出path
时,path
似乎仍然是空的。这不是我作为Python新手所期望的。任何建议都会有帮助
尝试附加到路径,而不是每次递归迭代都初始化它:
而不是:
^{pr2}$这样,就不会在每次迭代时初始化列表,因此它不会是函数的局部变量。在
相关问题 更多 >
编程相关推荐