题解 | #迷宫问题#

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

#两个版本,一个DFS,一个回溯
#DFS
m, n = list(map(int, input().split()))
maze = []
for _  in range(m):
    maze.append(list(map(int, input().split())))

def dfs(i,j,history):
    maze[i][j]=1
    if i==m-1 and j==n-1:
        for item in history:
            print('(' + str(item[0]) + ',' + str(item[1]) + ')')
        return
    directions=[(1,0),(-1,0),(0,1),(0,-1)]
    for direction in directions:
        ni,nj=i+direction[0],j+direction[1]
        if 0<=ni<m and 0<=nj<n and maze[ni][nj]==0:
            dfs(ni,nj,history+[(ni,nj)])

history=[(0,0)]
dfs(0,0,history)

#回溯
m, n = list(map(int, input().split()))
maze = []
for _  in range(m):
    maze.append(list(map(int, input().split())))

def dfs(i,j):
    if i==m-1 and j==n-1:
        for item in history:
            print('(' + str(item[0]) + ',' + str(item[1]) + ')')
        return
    directions=[(1,0),(-1,0),(0,1),(0,-1)]
    for direction in directions:
        ni,nj=i+direction[0],j+direction[1]
        if 0<=ni<m and 0<=nj<n and maze[ni][nj]==0:
            maze[ni][nj]=1
            history.append((ni,nj))
            dfs(ni,nj)
            maze[ni][nj]=0
            history.pop()

history=[(0,0)]
maze[0][0]=1
dfs(0,0)

全部评论

相关推荐

头像
04-17 09:29
已编辑
湖南农业大学 后端
睡姿决定发型丫:本硕末9也是0offer,简历挂了挺多,只有淘天 美团 中兴给了面试机会,淘天二面挂,美团一面kpi面,中兴一面感觉也大概率kpi(虽然国企,但一面0技术纯聊天有点离谱吧)
点赞 评论 收藏
分享
WillingLing:查看图片
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务