题解 | #迷宫问题#Python解法一看就懂

迷宫问题

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

def get_path(pos, matrix):
    i, j = pos[0], pos[1]
    n, m = len(matrix), len(matrix[0])
    if not 0 <= i < n or not 0 <= j < m or not matrix[i][j] == 0: return
    global cur_path, res
    cur_path.append((i, j))
    if i == n - 1 and j == m - 1: #到达终点
        if not res or len(cur_path) < len(res): #若res为空或cur_path比res短
            res = list(cur_path)
            return
    matrix[i][j] = 1
    get_path([i + 1, j], matrix)
    get_path([i - 1, j], matrix)
    get_path([i, j + 1], matrix)
    get_path([i, j - 1], matrix)
    matrix[i][j] = 0
    cur_path.pop()


while True:
    try:
        N, M = map(int, input().split())
        matrix = []
        for _ in range(N):
            matrix.append(list(map(int, input().split())))
        cur_path, res = [], []
        get_path([0,0], matrix)
        #print(res)
        for pos in res:
            print('({},{})'.format(pos[0], pos[1])) #要输出成字符形式
    except:
        break
全部评论

相关推荐

不愿透露姓名的神秘牛友
07-11 11:22
怎么这么多逆天求职者,救救我救救我救救我😭
flmz_Kk:哈哈哈哈哈哈,这么多求职者,肯定有那一两个逆天的
点赞 评论 收藏
分享
点赞 评论 收藏
分享
Beeee0927:是缅甸园区吗
点赞 评论 收藏
分享
评论
2
收藏
分享

创作者周榜

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