zoukankan      html  css  js  c++  java
  • python之迷宫DFS

    # @File: maze_stack_dfs
    
    
    maze = [
        [1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
        [1, 0, 0, 1, 0, 0, 0, 1, 0, 1],
        [1, 0, 0, 1, 0, 0, 0, 1, 0, 1],
        [1, 0, 0, 0, 0, 1, 1, 0, 0, 1],
        [1, 0, 1, 1, 1, 0, 0, 0, 0, 1],
        [1, 0, 0, 0, 1, 0, 0, 0, 0, 1],
        [1, 0, 1, 0, 0, 0, 1, 0, 0, 1],
        [1, 0, 1, 1, 1, 0, 1, 1, 0, 1],
        [1, 1, 0, 0, 0, 0, 0, 0, 0, 1],
        [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
    ]
    
    dirs = [
        lambda x, y: (x, y + 1),  #
        lambda x, y: (x + 1, y),  #
        lambda x, y: (x, y - 1),  #
        lambda x, y: (x - 1, y),  #
    ]
    
    
    # DFS depth first search
    def solve_maze_with_stack(x1, y1, x2, y2):
        stack = []
        stack.append((x1, y1))
        maze[x1][y1] = 2  # 表示已经走过的路
        while len(stack) > 0:
            cur_node = stack[-1]
            if cur_node == (x2, y2):
                print(stack)
                return True
            for d in dirs:
                next_x, next_y = d(*cur_node)
                if maze[next_x][next_y] == 0:
                    stack.append((next_x, next_y))
                    maze[next_x][next_y] = 2
                    break
            else:
                stack.pop()
        print('无路可走')
        return False
    
    
    solve_maze_with_stack(1, 1, 8, 8)
  • 相关阅读:
    memcache 应用场景
    如何写接口文档(登录)
    PHP常见错误级别及错误码
    ex33 while 循环
    ex32 循环和列表
    ex31--作出决定
    ex29-30 if,elif and else.
    ex28 布尔表达式练习
    ex25 更多更多的实践
    ex21 函数可以返回某些东西
  • 原文地址:https://www.cnblogs.com/xiao-xue-di/p/10168823.html
Copyright © 2011-2022 走看看