题解 | 迷宫寻路
迷宫寻路
https://www.nowcoder.com/practice/0c8930e517444d04b426e9703d483ed4
def solve(maze, start, end):
def is_valid(x, y):
return 0 <= x <len(maze) and 0 <= y <len(maze[0]) and maze[x][y]=='.'
def dfs(x, y, path):
if (x, y) == end:
return path
directions = [(1,0),(0,1),(-1,0),(0,-1)]
for dx, dy in directions:
new_x, new_y = x + dx , y + dy
if is_valid(new_x, new_y) and (new_x, new_y) not in path:
result = dfs(new_x, new_y, path +[(new_x,new_y)])
if result:
return result
return None
return dfs(start[0], start[1],[start])
if __name__ == "__main__":
n,m = map(int, input().split())
maze = [list(input().strip()) for _ in range(n)]
if solve(maze,(0,0),(n-1,m-1)):
print('Yes')
else:
print('No')


