迷宫
迷宫
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)