我有一個遞歸函數與數組作爲存儲路徑,當我旅行網格,從(0,0)到(x,y),我有當我在最後打印出path
以跳過被定義爲「不可用」Python - 瞭解變量傳遞的範圍遞歸函數
我實現我的功能這樣
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
仍然是空的。這不是我期望的Python新手。任何建議將是有益的
那麼,你的旅行函數只返回'True' /'False',所以'path'變化停留在遞歸步驟的範圍內。 – Fejs
這在Java中是不同的,它允許您按照遞歸步驟修改參數。回到軌道時,調用者應該能夠獲得傳遞給子遞歸步驟的參數的更新值? –