题解 | #迷宫问题#
迷宫问题
https://www.nowcoder.com/practice/cf24906056f4488c9ddb132f317e03bc
path = [] # load data from ex. m,n = map(eval,input().split()) maze = [] for i in range(m): maze.append(list(map(eval,input().split()))) # struct of the cord class pos: def __init__(self,x,y): self.x = x self.y = y # implement the dfs def dfs(maze,x,y,path): path.append(pos(x,y)) maze[x][y]=1 # dfs 返回 true 表示遍历到了结果 if x==(len(maze)-1) and y==(len(maze[0])-1): return True # 从四个方向检查是否满足边界约束/墙体约束 if x-1>=0 and maze[x-1][y]==0: if dfs(maze,x-1,y,path): return True if x+1<len(maze) and maze[x+1][y]==0: if dfs(maze,x+1,y,path): return True if y-1>=0 and maze[x][y-1]==0: if dfs(maze,x,y-1,path): return True if y+1<len(maze[0]) and maze[x][y+1]==0: if dfs(maze,x,y+1,path): return True path.pop() maze[x][y] = 0 return False # main dfs(maze,0,0,path) for i in range(len(path)): print(f"({path[i].x},{path[i].y})")