题解 | #迷宫问题#

迷宫问题

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
全部评论

相关推荐

01-26 22:20
已编辑
门头沟学院 Java
Java抽象带篮子:项目很nb了,现在好好准备八股和算法吧,早点找实习,可以看看我的置顶帖子。帖子里写了怎么改简历,怎么包装实习经历,还有2个高质量可速成的项目话术,和我的牛客八股笔记专栏
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务