Dijkstra算法
"""
Dijkstra1算法
采用邻接表,边数e,点数v
复杂度O(eloge)
"""
def Dijkstra1(graph, start, end):
m = len(graph)
S, T = [], [i for i in range(m)]
dis = [float('inf') for _ in range(m)]
hq = []
heapq.heappush(hq, (0, start))
while hq:
d, idx = heapq.heappop(hq)
if idx in S:
continue
dis[idx] = d
S.append(idx)
T.remove(idx)
for g, d in graph[idx]:
if dis[idx] + d < dis[g]:
dis[g] = dis[idx] + d
heapq.heappush(hq, (dis[g], g))
return dis
graph = [
[(1,4), (2,3)],
[(2,6), (3,7)],
[(3,6), (4,7)],
[(4,6), (5,7)],
[(5,6), (6,7)],
[(6,2)],
[]
]
print(Dijkstra(graph, 0, 3))