📅  最后修改于: 2023-12-03 15:00:24.888000             🧑  作者: Mango
Dijkstra算法是一种用于计算图中最短路径的贪心算法。该算法使用一个优先队列来存储每个节点的距离值,并选取距离值最小的节点进行遍历,继续更新其它节点。
dijkstra(G, s):
Q = set() # 存储所有未访问的节点
dist = {}
prev = {}
for v in G:
dist[v] = INFINITY # 初始值为无穷大
prev[v] = None
Q.add(v)
dist[s] = 0
while Q:
u = min(Q, key=dist.get) # 选取距离值最小的节点进行遍历
Q.remove(u)
for v in G[u]:
alt = dist[u] + G[u][v]
if alt < dist[v]:
dist[v] = alt
prev[v] = u
return dist, prev
下面是Python代码实现Dijkstra算法:
def dijkstra(graph, start):
"""
使用Dijkstra算法计算有向图中的最短路径。
:param graph: 图以邻接矩阵的形式表示
:param start: 起点
:return: 包含最短路径的字典
"""
# 记录每个节点的距离值和上一个节点
dist = {node: float('inf') for node in graph}
prev = {node: None for node in graph}
# 初始值
dist[start] = 0
unvisited = set(graph)
while unvisited:
# 选取距离值最小的节点进行遍历
current = min(unvisited, key=lambda node: dist[node])
# 遍历其它节点
for neighbor, cost in graph[current].items():
new_cost = dist[current] + cost
if new_cost < dist[neighbor]:
dist[neighbor] = new_cost
prev[neighbor] = current
unvisited.remove(current)
return dist, prev
下面是一个使用示例,使用了一个包含6个节点和6条边的有向图:
graph = {
'A': {'B': 10, 'D': 5},
'B': {'C': 1, 'E': 3},
'C': {'F': 2},
'D': {'B': 3, 'E': 9},
'E': {'C': 4, 'F': 2},
'F': {'A': 7},
}
dist, prev = dijkstra(graph, 'A')
print(dist)
# Output: {'A': 0, 'B': 8, 'C': 9, 'D': 5, 'E': 12, 'F': 11}
path = []
current = 'F'
while current:
path.append(current)
current = prev[current]
print(' -> '.join(path[::-1]))
# Output: F -> A -> D
Dijkstra算法是一种实用性较高的算法,在计算图中的最短路径时有很好的效率和表现。对于新手来说也比较容易理解,非常适合入门练习。