迪杰斯特拉算法(Dijkstra)是由荷兰计算机科学家狄克斯特拉于1959 年提出的,因此又叫狄克斯特拉算法。是从一个顶点到其余各顶点的最短路径算法,解决的是有权图中最短路径问题
。迪杰斯特拉算法主要特点是以起始点为中心向外层层扩展,直到扩展到终点为止。
该算法的目标:带权图求最短路径
对于带权图需要借助优先队列来实现。
python提供了优先队列这种结构,参考如下:
import heapq
#PriorityQueue
pqueue = []
heapq.heappush(pqueue, (1, 'A'))
heapq.heappush(pqueue, (7, 'B'))
heapq.heappush(pqueue, (3, 'C'))
heapq.heappush(pqueue, (6, 'D'))
heapq.heappush(pqueue, (2, 'E'))
while len(pqueue) > 0:
print(heapq.heappop(pqueue))
代码实现:
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}
for vertex in graph:
if vertex != s:
distance[vertex]=math.inf
return distance
# s代表开始的结点
def dijkstra(graph, s):
pqueue = []
heapq.heappush(pqueue,(0, s))
seen = set() #定义一个集合
parent = {s: None}
distance = {s: 0}
distance = init_distance(graph, s)
while len(pqueue)>0:
pair = heapq.heappop(pqueue)
dist = pair[0]
vertex = pair[1]
seen.add(vertex)
nodes = graph[vertex].keys()
for w in nodes:
if w not in seen:
if (dist + graph[vertex][w])< distance[w]:
heapq.heappush(pqueue, (dist + graph[vertex][w], w))
parent[w] = vertex
distance[w] = dist + graph[vertex][w]
# print(vertex)
return parent, distance
# parent = BFS(graph, 'E')
# print(parent)
# v = 'B'
# while v!= None:
# print(v)
# v = parent[v]
parent, distance = dijkstra(graph, 'A')
print(parent, distance)
整理自:https://www.bilibili.com/video/av25829980/?spm_id_from=333.788.videocard.1