题解 | #迷宫问题#

迷宫问题

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

while True:
    try:
        m,n = map(int,input().split())
        matrix = []
        for i in range(m):
            d = list(map(int,input().split()))
            #print(c)
            matrix.append(d)
            
        def dfs(path):
            if path[-1] == [m-1,n-1]:
                return path
            r, c = path[-1]
            matrix[r][c] = 2
            directions = [[r+1,c],[r,c+1],[r-1,c],[r,c-1]]
            for i,j in directions:
                if 0<=i<m and 0<=j<n and matrix[i][j]==0:
                    final_path = dfs(path+[[i,j]])
                    if final_path[-1] == [m-1,n-1]:
                        return final_path
            return path#很重要,保证输出
        
                    
        path = dfs([[0,0]])
        for i in path:
            print('({},{})'.format(i[0],i[1]))
       
    except:
        break
全部评论

相关推荐

点赞 评论 收藏
分享
2 收藏 评论
分享
牛客网
牛客企业服务