栈和队列_迷宫问题_队列

#队列
class QueueUnderflow(ValueError):
    pass

class SQueue():
    def __init__(self,init_len=8):
        self._len = init_len
        self._elems = [0]*init_len
        self._head = 0
        self._num = 0

    def is_empty(self):
        return self._num == 0
    #查看队顶
    def peek(self):
        if self._num == 0:
            raise QueueUnderflow
        return self._elems[self._head]
    #出队
    def dequeue(self):
        if self._num == 0:
            raise QueueUnderflow
        e = self._elems[self._head]
        self._head = (self._head+1)%self._len
        self._num = self._num -1
        return e

    def enqueue(self,e):
        if self._num == self._len:
            self.__extend()
        self._elems [(self._head + self._num) % self._len] = e
        self._num+=1

    def __extend(self):
        old_len=self._len
        new_elems = [0]*self._len
        for i in range(old_len):
            new_elems[i] = self._elems[(self._head+i)%old_len]
            self._elems,self._head = new_elems,0
#定义maze
line_0 = [1,1,1,1,1,1,1]
line_1 = [1,1,1,1,0,1,1]
line_2 = [1,1,0,1,1,1,1]
line_3 = [1,1,0,0,0,1,1]
line_4 = [1,1,0,1,0,0,1]
line_5 = [1,1,0,1,1,1,1]
line_6 = [1,1,1,1,1,1,1]
maze=[line_1,line_1,line_2,line_3,line_4,line_5,line_6]
#方向
dirs = [(0,1),(1,0),(0,-1),(-1,0)]
def mark(maze,pos):
    #定义到过了=2  maze是迷
    maze[pos[0]][pos[1]]  = 2
def passable (maze,pos):
    return maze[pos[0]][pos[1]] == 0


def maze_solver_queue(maze,start,end):
    if start == end:
        print ('path finds.')
        return
    qu = SQueue()
    mark(maze,start)
    qu.enqueue(start)
    if qu.is_empty():print ('null')
    while not qu.is_empty():
        pos = qu.dequeue()
        print (pos)
        for i in range(4):
            nextp = (pos[0] + dirs[i][0], pos[1] + dirs[i][1])
            if passable(maze,nextp):
                if nextp == end:
                    print('path find.')
                    return
                mark(maze,nextp)
                qu.enqueue(nextp)
    print ('find no path')


maze_solver_queue(maze,(5,2),(4,5))
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值