'''
Author:Lihao Liu
功能:实现最短路径算法
参数:
sNode:源节点
dNode:目标节点
adjacencyMatrix:网络的邻接矩阵(不连接的地方标0)
'''
def DijkstraRoad(sNode, dNode, adjacencyMatrix):
path = [] # s-d的最短路径
n = len(adjacencyMatrix) # 邻接矩阵维度,即节点个数
fmax = 999
w = [[0 for i in range(n)] for j in range(n)] # 邻接矩阵转化成维度矩阵 n*n阶矩阵
book = [0 for i in range(n)] # 是否已经是最小的标记列表
dis = [fmax for i in range(n)] # s到其他节点的最小距离
book[sNode] = 1
midpath = [-1 for i in range(n)] # 上一跳列表
for i in range(n):
for j in range(n):
if adjacencyMatrix[i][j] != 0:
# i,j间有路径
w[i][j] = adjacencyMatrix[i][j]
else:
# i,j间没路径
w[i][j] = fmax
if i == sNode and adjacencyMatrix[i][j] != 0:
dis[j] = adjacencyMatrix[i][j] # i,j的距离
for i in range(n - 1): # n-1次遍历,除了s节点
min = fmax
u = 0
for j in range(n):
if book[j] == 0 and dis[j] < min: # 如果未遍历且距离最小
min = dis[j]
u = j
book[u] = 1
for v in range(n): # u直连的节点遍历一遍
if dis[v] > dis[u] + w[u][v]:
dis[v] = dis[u] + w[u][v]
midpath[v] = u # 上一跳更新
j = dNode # j是序号
path.append(dNode) # 因为存储的是上一跳,所以先加入目的节点d,最后倒置
while (midpath[j] != -1):
path.append(midpath[j])
j = midpath[j]
path.append(sNode)
path.reverse() # 倒置列表
return path, dis[dNode]
'''test'''
# adjacencyMatrix=[
# [0,2,4],
# [2,0,1],
# [4,1,0]
# ]
# path, dis = DijkstraRoad(0,2,adjacencyMatrix)
# print(path)
# print(dis)
03-25
1011
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)