Dijkstra 算法描述如下:
设:
c(i,j): 结点 i 至结点 j 之间链路的代价,若 i,j 不直接相连,则为无穷大。
D(v): 当前从源结点至目的结点 V 之间路由的代价。
p(v): 从源结点至目的结点 V 之间路由中 V 之前的结点
N: 已经知道最优路径的结点集合
1 Initialization:
2 N = {A}
3 for all nodes v
4 if v adjacent to A
5 then D(v) = c(A,v)
6 else D(v) = infty
725
8 Loop 9 find w not in N such that D(w) is a minimum
10 add w to N
11 update D(v) for all v adjacent to w and not in N:
12 D(v) = min( D(v), D(w) + c(w,v) )
13 /* new cost to v is either old cost to v or known
14 shortest path cost to w plus cost from w to v */
15 until all nodes in N
源代码:
import heapq
#????? 对应的链路代价
X1 = ?
X2 = ?
X3 = ?
X4 = ?
X5 = ?
X6 = ?
X7 = ?
X8 = ?
# 邻接矩阵
graph = [
# u v w x y z
[0, X1, 3, 2, 0, 0], # u -> v (2), u -> w (3), u -> x (2)
[X1, 0, X3, X2, 0, 0], # v -> u (2), v -> w (2), v -> x (1)
[3, X3, 0, X4, X6, X7],# w -> u (3), w -> v (2), w -> x (8), w -> y (1), w -> z (9)
[2, X2, X4, 0, X5, 0], # x -> u (2), x -> v (1), x -> w (8), x -> y (1)
[0, 0, X6, X5, 0, X8], # y -> w (1), y -> x (1), y -> z (2)
[0, 0, X7, 0, X8, 0] # z -> w (9), z -> y (2)
]
node_map = ['u', 'v', 'w', 'x', 'y', 'z']
def dijkstra(matrix, start):
n = len(matrix)
distances = [float('infinity')] * n
distances[start] = 0
priority_queue = [(0, start)]
shortest_path = {i: [] for i in range(n)}
shortest_path[start] = [node_map[start]]
visited = set()
while priority_queue:
current_distance, current_node = heapq.heappop(priority_queue)
if current_node in visited:
continue
visited.add(current_node)
print(f"当前最近点:{node_map[current_node]},路径长度:{current_distance}")
for neighbor in range(n):
if matrix[current_node][neighbor] > 0 and neighbor not in visited:
distance = current_distance + matrix[current_node][neighbor]
if distance < distances[neighbor]:
distances[neighbor] = distance
heapq.heappush(priority_queue, (distance, neighbor))
shortest_path[neighbor] = shortest_path[current_node] + [node_map[neighbor]]
print(f"从初始点到各点的当前最短路径长度:{distances}")
print(f"从初始点到各点的当前最短路径:{shortest_path}")
return distances, shortest_path
start_node = 0 # 假设从u开始
distances, shortest_path = dijkstra(graph, start_node)
print("最终最短距离:", distances)
print("最终最短路径:", shortest_path)