正在打开模型库
正在打开模型库
在网络中找两点之间距离、时间或费用最小的一条路。
从起点一层层扩展,永远先走当前已知最短的那个点。
题面是点与路、要你给出具体走法时用。
Python 代码
import heapq
graph = {0: [(1, 2), (2, 5)], 1: [(2, 1), (3, 3)], 2: [(3, 2)], 3: []}
def dijkstra(start):
dist = {start: 0}
pq = [(0, start)]
while pq:
d, u = heapq.heappop(pq)
if d != dist[u]:
continue
for v, w in graph[u]:
nd = d + w
if nd < dist.get(v, 1e18):
dist[v] = nd
heapq.heappush(pq, (nd, v))
return dist
print(dijkstra(0))