python的,大佬求助!!!就拿了40

B3625 迷宫寻路

lzysxfcs @ 2024-04-16 21:53:21

def dfs(x, y):
    if x == n and y == m:
        return True
    # 当前位置标记为已访问
    visited[x][y] = True
    directions = [(0, 1), (0, -1), (1, 0), (-1, 0)]
    for d in directions:
        # 移动后的新位置
        new_x, new_y = x + d[0], y + d[1]
        # 在范围内,未访问,是空地
        if 1 <= new_x <= n and 1 <= new_y <= m and not visited[new_x][new_y] and maze[new_x][new_y] == '.':
            # 如果新位置符合条件,递归调用 dfs 函数
            if dfs(new_x, new_y):
                return True
    return False

n, m = map(int, input().split())
maze = [input() for _ in range(n)]
visited = [[False] * m for _ in range(n+1)]
if dfs(0, 0):
    print('Yes')
else:
    print('No')

|