迷宮app
def initMaze(): maze = [[0] *7 for _ in range(5 + 2)] wall = ( (1,3),(1,5), (2,1),(2,5), (3,3),(3,4), (4,2), (5,4) ) for i in range(7): # 周邊設牆 maze[0][i] = maze[i][0] = 1 maze[i][-1] = maze[-1][i] = 1 for x,y in wall: maze[x][y] = 1 for l in maze: print(l) print("================") return maze def go(maze,start,end): """ :param maze: 迷宮 :param start: 起點 :param end: 終點 :return: 迷宮路徑 """ x, y = start # 起點 ex, ey = end # 終點 stack = [(x,y)] # 路徑 maze[x][y] = 1 # 走過的路徑設置爲1 while stack: x , y = stack[-1] # 獲取當前位置 if (x,y) == (ex,ey): break for i,j in [(0,1),(1,0),(0,-1),(-1,0)]: # 向不一樣的方向移動 if maze[x+i][y+j] == 0: # 若是到了是通的 maze[x+i][y+j] = 1 # 設置已走過的位置爲1 stack.append((x+i,y+j)) # 添加路徑 # print(x,y) break else: stack.pop() # 若是到了死衚衕,則回退一步 return stack Amze = initMaze() ret = go(Amze,(1,1),(5,5)) print(ret)