题解 | #HJ43 迷宫问题#

迷宫问题

https://www.nowcoder.com/practice/cf24906056f4488c9ddb132f317e03bc

def walk(i, j, path):
    if (j+1 < n) and (maze[i][j+1] == 0) and ((i, j+1) not in path): # 向右可以走 且 没走过
        walk(i, j+1, path + [(i, j+1)])
    if (j-1 >= 0) and (maze[i][j-1] == 0) and ((i, j-1) not in path): # 向左可以走 且 没走过
        walk(i, j-1, path + [(i, j-1)])
    if (i+1 < m) and (maze[i+1][j] == 0) and ((i+1, j) not in path): # 向下可以走 且 没走过
        walk(i+1, j, path + [(i+1, j)])
    if (i-1 >= 0) and (maze[i-1][j] == 0) and ((i-1, j) not in path): # 向上可以走 且 没走过
        walk(i-1, j, path + [(i-1, j)])
    if (i, j) == (m-1, n-1): # 到达出口
        for p in path:
            print(f"({p[0]},{p[1]})")

while True:
    try:
        m, n = list(map(int, input().split()))
        maze = [[i for i in map(int, input().split())] for _ in range(m)]
        path = [(0,0)]
        walk(0, 0, path)
    except:
        break
全部评论

相关推荐

11-18 09:44
Java
小白也想要offer:简历别放洋屁,搞不还还放错了,当然你投外企除外,以上纯属个人观点
点赞 评论 收藏
分享
评论
8
5
分享
牛客网
牛客企业服务