题解 | 【模板】单源最短路1

【模板】单源最短路1

https://www.nowcoder.com/practice/f24504c9ff544f7c808f76693cc34af8

import sys, heapq
# import heapq

def mini_path(n,m,adj):

    D = [float('inf')]*(5000+1)
    # print(D)
    D[1] = 0
    heap =[]
    heapq.heappush(heap,(0,1))

    while heap:
        # pop minimum element determined by 1st entry
        current_D, u = heapq.heappop(heap) 
        if u == n:
            return current_D
        if current_D > D[u]:
            continue
        for v in adj[u]:
            if current_D+1 < D[v]:
                D[v]=current_D+1
                heapq.heappush(heap, (D[v],v))
           

    return -1

a = sys.stdin.read().split()
n,m = int(a[0]), int(a[1])

idx = 2
edge = []
adj = [[] for _ in range(5000+1)]
for _ in range(m):
    u,v = int(a[idx]), int(a[idx+1])

    adj[u].append((v))
    adj[v].append((u))
    idx += 2

path = mini_path(n,m,adj)
print(path)


全部评论

相关推荐

不愿透露姓名的神秘牛友
07-10 11:31
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
07-11 15:37
点赞 评论 收藏
分享
06-10 21:15
门头沟学院 Java
宁阿:好多这种没🧠的公司,他们估计都不知道毕业的人不能给安排实习岗
实习吐槽大会
点赞 评论 收藏
分享
自学java狠狠赚一...:骗你点star的,港卵公司,记得把star收回去
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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