#队列 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))
栈和队列_迷宫问题_队列
最新推荐文章于 2021-09-01 13:02:09 发布