题解 | #迷宫问题#

迷宫问题

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

全部评论

相关推荐

不愿透露姓名的神秘牛友
06-29 17:30
点赞 评论 收藏
分享
认真搞学习:这么良心的老板真少见
点赞 评论 收藏
分享
牛客383479252号:9,2学生暑期实习失利开始投小厂,给这群人整自信了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务