棧和佇列_迷宮問題_遞迴
阿新 • • 發佈:2019-01-30
#迷宮問題---棧和佇列 #定義maze line_0 = [1,1,1,1,1,1,1] line_1 = [1,1,0,1,1,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 find_path(maze,pos,end): mark(maze,pos) if pos == end: return True else: for i in range(4): nextp = pos[0]+dirs[i][0],pos[1]+dirs[i][1] #下一方向 if passable(maze,nextp): find_path(maze,nextp,end) print(nextp) return True return False find_path(maze,[5,2],[4,5]) print (maze)