题解 | #迷宫问题#

迷宫问题

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

def dfs(x,y,path):
    if x==m-1 and y==n-1:
        return path
    paths=[]
    if x-1>=0 and graph[x-1][y]==0 and (x-1,y) not in path:
        paths.extend(dfs(x-1,y,path+[(x-1,y)]))
    if x+1<=m-1 and graph[x+1][y]==0 and (x+1,y) not in path:
        paths.extend(dfs(x+1,y,path+[(x+1,y)]))
    if y-1>=0 and graph[x][y-1]==0 and (x,y-1) not in path:
        paths.extend(dfs(x,y-1,path+[(x,y-1)]))
    if y+1<=n-1 and graph[x][y+1]==0 and (x,y+1) not in path:
        paths.extend(dfs(x,y+1,path+[(x,y+1)]))
    return paths    
while True:
    try:
        number=list(map(int,input().split()))
        m=number[0]
        n=number[1]
        graph=[]
        for i in range(m):
            graph.append(list(map(int,input().split())))
        path=[(0,0)]
        res=dfs(0,0,path)
        print("\n".join([f"({x},{y})" for x, y in res])) 
    except:
        break

全部评论

相关推荐

totoroyyw:千年老妖😂
投递华为等公司10个岗位
点赞 评论 收藏
分享
Hello_WordN:咱就是说,除了生命其他都是小事,希望面试官平安,希望各位平时也多注意安全
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务