V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
elmliu
V2EX  ›  Python

关于 Python 递归时修改全局变量失败的问题

  •  
  •   elmliu · 2018-09-23 18:07:12 +08:00 · 1454 次点击
    这是一个创建于 2034 天前的主题,其中的信息可能已经有所发展或是发生改变。
    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...
    Philippa
        1
    Philippa  
       2018-09-23 18:25:03 +08:00
    从新弄一个在线的 playground 版本的代码吧,尤其 Python 这种依赖缩进语言,10 个人有 9.99 个没耐心看这种没排版的代码。随手一搜,比如这个: https://www.katacoda.com/courses/python/playground
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5485 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 29ms · UTC 06:06 · PVG 14:06 · LAX 23:06 · JFK 02:06
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.