题解 | #迷宫问题#

迷宫问题

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

尝试在回溯时处理死路情况,主要实现参考下面代码https://blog.nowcoder.net/n/478eaf14b4b246ac9d6d31f313493690

while True:
    try:
        row, col = [int(x) for x in input().split(' ')]
        maze = []
        for i in range(row):
                maze.append([int(x) for x in input().split(' ')])
        #按行分割数据构建迷宫 
        
        lst = [(0,0)]#路径点
        while lst:
            if lst[-1] == (row-1, col-1):#终点判断
                for i in lst:
                    print('(%d,%d)'%(i))
                break
            i, j = lst[-1]#未到终点回溯一步
            maze[i][j] = 2#标记走过点
            
            count = 0#有效路径点计数
            check = []#有效路径内容统计
            if i-1>=0:
                count +=1
                check.append(maze[i-1][j])
            if i+1<row:
                count +=1
                check.append(maze[i+1][j])
                
            if j-1>=0:
                count +=1   
                check.append(maze[i][j-1])
            if j+1<col:
                count +=1
                check.append(maze[i][j+1])
            
            wall_walked = check.count(2) + check.count(1)
            #存在的0已经走过,且该0是除2外唯一0,则继续回溯
            if( wall_walked == count):
                lst.pop()
                i, j = lst[-1]#未到终点回溯一步
                maze[i][j] = 2#标记走过点
                
                
            if i-1 >= 0 and maze[i-1][j] == 0:#
                lst.append((i - 1, j))
                continue
            elif i+1 < row and maze[i+1][j] == 0:
                lst.append((i + 1, j))
                continue   
            elif j+1 < col and maze[i][j+1] == 0:
                lst.append((i, j+1))
                continue   
            elif j-1 >= 0 and maze[i][j - 1]==0:
                lst.append((i, j - 1))
                continue
            else:
                 lst.pop()
        else:
            print('This is a maza that can not be finished')
    except:
        break
全部评论

相关推荐

不愿透露姓名的神秘牛友
昨天 11:24
大家还是用ai改吧,我心疼得要死,就当花钱买教训吧,人家直接拿完钱就跑路了
程序员小白条:简历修改700....神奇,又不是帮你面试,咋的,简历修改从双非变92了还是没实习变成有大厂实习了
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
07-08 14:08
点赞 评论 收藏
分享
06-12 16:00
天津大学 Java
牛客30236098...:腾讯坏事做尽,终面挂是最破防的 上次被挂了后我连简历都不刷了
点赞 评论 收藏
分享
05-20 13:59
门头沟学院 Java
米黑子米黑子:你这个成绩不争取下保研?
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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