Dijkstra(迪杰斯特拉算法)
#Dijkstra(迪杰斯特拉算法) 带权无向图中寻求最短路径
#动态演示过程: https://www.bilibili.com/video/BV1q4411M7r9?from=search&seid=5585063956337033177
#实现的话用优先队列实现(出队的都是确认是到该点的最短路径)
import heapq
import math
graph = {
"A": {"B": 5, "C": 1},
"B": {"A": 5, "C": 2, "D": 1},
"C": {"A": 1, "B": 2, "D": 4, "E": 8},
"D": {"B": 1, "C": 4, "E": 3, "F": 6},
"E": {"C": 8, "D": 3},
"F": {"D": 6}
}
def init_distance(graph,s):
distance = {s:0}
nodes = graph.keys()
for node in nodes:
if node !=s:
distance[node] = math.inf
return distance
def dijkstra(graph,s):
#用heapq(小根堆)实现优先队列
pqueue = []
heapq.heappush(pqueue,(0,s))
#此处的seen和BFS,DFS中的seen不一样,此处的seen都是出队的,已经确认最短路径的节点
seen = set()
# A B C D E F
#distance(初始化位正无穷)
#parent(初始化为-1)
distance = init_distance(graph,s)
parent = {s:None}
#出队的都是已经确认是最短距离的
while len(pqueue) > 0:
pair = heapq.heappop(pqueue)
dist = pair[0]
cur = pair[1]
seen.add(cur)
#与cur相邻的节点
nodes = graph[cur].keys()
for n in nodes:
if n not in seen:
#满足下面关系式才更新
if dist + graph[cur][n] < distance[n]:
heapq.heappush(pqueue,(dist + graph[cur][n],n))
parent[n] = cur
distance[n] = dist + graph[cur][n]
return parent, distance