队列-广度优先队列

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]
]
for i in maze:
    print(i,end='\n')

# dirs = [    #右下左上的顺序
#     lambda x, y: (x+1, y),
#     lambda x, y: (x-1, y),
#     lambda x, y: (x, y-1),
#     lambda x, y: (x, y+1),
# ]
dirs=[       #左右上下
lambda x, y: (x - 1, y),
    lambda x, y: (x, y + 1),
    lambda x, y: (x + 1, y),
    lambda x, y: (x, y - 1),
]

from collections import deque
def print_r(path):
    curnode = path[-1]   #取栈顶(终点)  是真实路径上的点
    realpath=[]
    while curnode[2] !=-1:       #
        realpath.append(curnode[0:2])
        curnode=path[curnode[2]]
    realpath.append(curnode[0:2]) #起点
    realpath.reverse()
    for node in realpath:
        print(node)

def path_deque(x1,y1,x2,y2):
    queue=deque()
    queue.append((x1,y1,-1))   #-1表示放在起点开始
    path = []    #放出栈头的元素
    while len(queue) >0:
        curnode =queue.popleft()  #出栈头元素
        path.append(curnode)   #记录出栈的元素,
        if curnode[0]==x2 and curnode[1]==y2:
            #终点
            print_r(path)
            return True
        for dir in dirs:
            nextnode = dir(curnode[0],curnode[1])
            if maze[nextnode[0]][nextnode[1]]==0:
                queue.append((nextnode[0],nextnode[1],len(path)-1))   #后续节点进队,记录哪个节点带它来的
                maze[nextnode[0]][nextnode[1]]=2
    else:
        print("没有错")
        return False
path_deque(1,1,8,8)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值