关于 Python 递归时修改全局变量失败的问题
2018-09-23 18:07:12 +08:00
elmliu
def dfs_maze(path, target):
global paths
maze = [[" ","#","#"," "," "],[" "," "," ","#"," "],["#"," "," ","#"," "],[" "," "," ","#","#"],[" "," "," "," "," "]]
if path[-1] == target:
paths.append(path)
print(path)
return
for each in [[0,1], [0,-1], [1, 0], [-1, 0]]:
node = [path[-1][0] + each[0], path[-1][1] + each[1]]
if -1 not in node and 5 not in node and node not in path and maze[node[0]][node[1]] != '#':
path.append(node)
dfs_maze(path, target)
path.pop(-1)
def main():
dfs_maze([[0,0]], [4, 4])
for each in paths:
print(each)
paths = []
main()
就是一个深搜解决迷宫最短路径的函数,path 是一个二维数组,储存已经走过的每一个点,target 是终点。在边界条件满足时,打印出来的路径是没问题的。但在深搜结束后,打印出来的 paths 是一堆[[0,0]]的二维数组,这是为何?
不知为啥没有代码排版,sorry...
1 条回复
这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。
https://www.v2ex.com/t/491971
V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。
V2EX is a community of developers, designers and creative people.