题解 | 【模板】单源最短路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)


全部评论

相关推荐

06-02 15:17
门头沟学院 Java
心爱的idea:怎么会呢 应该是打招呼有问题 问就说实习6个月全国可飞随时到岗
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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