递归+最短路径 | HJ43 迷宫问题

import copy
def func(migong, i, j, path):
    if (i, j) == (n-1, m-1):
        res.append(copy.deepcopy(path))
        return
    if j+1 < m and migong[i][j+1] != '1' and (i,j+1)not in path:
        path.append((i, j+1))
        func(migong, i, j+1, path)
        path.pop()
    if i+1 < n and migong[i+1][j] != '1' and (i+1,j)not in path:
        path.append((i+1, j))
        func(migong, i+1, j, path)
        path.pop()
    if j-1 >= 0 and migong[i][j-1] != '1' and (i,j-1)not in path:
        path.append((i, j-1))
        func(migong, i, j-1, path)
        path.pop()
    if i-1 >= 0 and migong[i-1][j] != '1' and (i-1,j)not in path:
        path.append((i-1, j))
        func(migong, i-1, j, path)
        path.pop()

while True:
    try:
        n, m = list(map(int, input().split(' ')))
        migong = []
        res = []
        for _ in range(n):
            migong.append(input().split(' '))
        func(migong, 0, 0, [(0,0)])
        min_length, min_path = n*m, None
        for path in res:
            if len(path) < min_length:
                min_length = len(path)
                min_path = path
        for node in min_path:
            print(f'({node[0]},{node[1]})')
    except:
        break

用时:40min

华为笔试刷题 文章被收录于专栏

高质量题: 1~40:HJ16,HJ22,HJ24,HJ26,HJ27,HJ28,HJ35,HJ37,HJ39; 40~80:HJ41,HJ42,HJ43,HJ44,HJ48,HJ50,HJ52,HJ53,HJ57,HJ61,HJ63,HJ64,HJ70,HJ71,HJ74,HJ77; 80~108:HJ82,HJ85,HJ88,HJ89,HJ93,HJ95,HJ98,HJ103,HJ107

全部评论

相关推荐

不愿透露姓名的神秘牛友
10-05 10:13
已编辑
HHHHaos:让这些老登来现在秋招一下,简历都过不去
点赞 评论 收藏
分享
真java练习生:他的回答真的是太糟糕了,就像隔壁苏珊婶婶做的苹果派一样
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务