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)
  • 相关阅读:
    mysql 配置
    idea 学会看log文件
    ac自动机(tree+kmp模板)
    矩阵快速幂(纯数学递推)
    矩阵快速幂(queue递推)
    RMQ(连续相同最大值)
    dp(过河问题)
    bfs(火星撞地球)
    相同子序列集合
    图博弈
  • 原文地址:https://www.cnblogs.com/xiao-xue-di/p/10168823.html
Copyright © 2011-2022 走看看