题解 | #迷宫问题#
迷宫问题
https://www.nowcoder.com/practice/cf24906056f4488c9ddb132f317e03bc
def findMazePath(maps): if not maps or not maps[0]: return 0 rows, cols = len(maps), len(maps[0]) directions = [(-1, 0), (0, -1), (1, 0), (0, 1)] # 记录已经访问过的单元格 visited = [[False for _ in range(cols)] for _ in range(rows)] path = [] def dfs(i, j): # 若为终点,返回True if i == rows - 1 and j == cols - 1: path.append((i,j)) return True # 记录已访问的单元格 visited[i][j] = True path.append((i,j)) for dx, dy in directions: x, y = i + dx, j + dy if 0 <= x < rows and 0 <= y < cols and not visited[x][y] and maps[x][y] == 0: if dfs(x, y): return True # 如果从当前点的所有方向都无法到达终点,从路径中移除此点,并回溯 path.pop() return False dfs(0, 0) return path def main(): rows, cols = map(int, input().split()) maps = [list(map(int, input().split())) for _ in range(rows)] path = findMazePath(maps) for x in path: print("(%d,%d)"%(x[0],x[1])) if __name__ == "__main__": main()