V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
推荐学习书目
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 · Sep 23, 2018 · 1862 views
    This topic created in 2774 days ago, the information mentioned may be changed or developed.
    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  
       Sep 23, 2018
    从新弄一个在线的 playground 版本的代码吧,尤其 Python 这种依赖缩进语言,10 个人有 9.99 个没耐心看这种没排版的代码。随手一搜,比如这个: https://www.katacoda.com/courses/python/playground
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   5882 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 31ms · UTC 02:48 · PVG 10:48 · LAX 19:48 · JFK 22:48
    ♥ Do have faith in what you're doing.