zoukankan      html  css  js  c++  java
  • 使用堆和队列数据结构解决迷宫问题

    python实现迷宫问题的栈和队列的解决方法:

    #迷宫问题
    #表示迷宫的颜色,0表示路通,1表示围墙
    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]
    ]

    d=[
    lambda x,y:(x+1,y),
    lambda x,y:(x-1,y),
    lambda x,y:(x,y+1),
    lambda x,y:(x,y-1)
    ]

    #方法1:使用来进行解决,方法是回溯法,即深度优先搜索,但是并非是最佳最短的路线
    def maze_path(x1,y1,x2,y2):
    stack=[]
    stack.append((x1,y1))
    while(len(stack)>0):
    curnode=stack[-1]
    if curnode[0]==x2 and curnode[1]==y2:
    for path in stack:
    print(path)
    return True
    for i in d:
    nextnode=i(curnode[0],curnode[1])
    #如果下一个位置可以走
    if maze[nextnode[0]][nextnode[1]]==0:
    stack.append(nextnode)
    maze[nextnode[0]][nextnode[1]]= 2 #2表示走过了
    break
    else:
    maze[nextnode[0]][nextnode[1]] =2
    stack.pop()
    else:
    print("没路")
    return False
    maze_path(1,1,8,8)

    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]
    ]
    #解决方法2:使用队列来进行记录,属于广度优先搜索
    from collections import deque #导入队列的内置模块
    #输出路径函数

    def print_r(path):
    real_path=[]
    i=len(path)-1
    while i>=0:
    real_path.append(path[i][0:2])
    i=path[i][2]
    real_path.reverse()
    for p in real_path:
    print(p)

    def maze_path1(x1,y1,x2,y2):
    quede=deque()
    path=[]
    quede.append((x1,y1,-1))
    while len(quede)>0:
    curnode=quede.popleft()
    path.append(curnode)
    if curnode[0]==x2 and curnode[1]==y2:
    #到达终点
    print_r(path)
    for dir in d:
    nextnode=dir(curnode[0],curnode[1])
    if maze[nextnode[0]][nextnode[1]]==0:
    quede.append((nextnode[0],nextnode[1],len(path)-1))
    maze[nextnode[0]][nextnode[1]] =2 #标记已经走过
    return False

    maze_path1(1,1,8,8)

  • 相关阅读:
    ruia笔记
    一个有趣的小例子,带你入门协程模块-asyncio
    python标准库之secrets
    转载:(Mac)在bash和zsh配置环境变量path的几种方法
    mac安装mysql8.0的错误
    Mac下的安装 mongodb
    mac 安装zsh教程资料
    mac 报错Root chmod operation not permitted on file
    喝奶粉的宝宝一天喝多少水 奶粉喂养的宝宝每天要喝多少水
    洗碗机耗材:finish 亮碟 产品的选购
  • 原文地址:https://www.cnblogs.com/Yanjy-OnlyOne/p/12433325.html
Copyright © 2011-2022 走看看