#-*- coding: cp936 -*- -*-
from sys import maxint
class shortestPath:
@staticmethod
def dijkstra(node,connected,origin,path,d):
#关键是 按路径长度递增 求得各顶点的路径
originIndex = node.index(origin)
#final[i] 为 True 表示 已经求得 源点 到 i 的最短路径
final = [ False for i in range(len(node))]
for i in range(len(node)):
d[i] = connected[originIndex][i]
if d[i] < maxint:
path[i][originIndex]=True
path[i][i]=True
d[originIndex]=0
final[originIndex]=True
path[originIndex][originIndex]=True
for i in range(len(node)-1):
mark=-1
minVal = maxint
#求得当前最短路径中的最小值,实现递增
for j in range(len(node)):
if not final[j]:
if d[j] < minVal:
mark = j
minVal = d[j]
final[mark]=True
#由于final 更新了,d 随之更新
for j in range(len(d)):
if (not final[j]) and minVal+connected[mark][j] < d[j]:
d[j]=minVal+connected[mark][j]
#更新 源点 到j 当前最短路径需要经过的点
for k in range(len(d)):
path[j][k]=path[mark][k]
path[j][j]=True #表明j点可达
shortestPath.printPath(node,originIndex,path,d)
@staticmethod
def printPath(node,originIndex,path,d):
for i in range(len(d)):
print("------------------------")
throughNode=[]
for j in range(len(d)):
if path[i][j]:
throughNode.append((d[j],j))
#按cost排序
throughNode.sort(key=lambda tup:tup[0])
if d[i]==maxint:
print(node[originIndex]+" and "+node[i]+" not connected")
else:
print(node[originIndex]+"->"+node[i]+" cost "+str(d[i]))
print("path is ...")
for each in throughNode:
print(node[each[1]])
def main():
#使用邻接矩阵来表示图
node = ['V0','V1','V2','V3','V4','V5']
connected = [[maxint,maxint, 10,maxint,30, 100],
[maxint,maxint, 5,maxint,maxint,maxint],
[maxint,maxint,maxint, 50,maxint,maxint],
[maxint,maxint,maxint,maxint,maxint, 10],
[maxint,maxint,maxint, 20,maxint, 60],
[maxint,maxint,maxint,maxint,maxint,maxint]]
#path[i][j]为True表示 j 是 源点到i 当前最短路径 的一个点
path = [[False for i in range(len(node))] for j in range(len(node))]
#d[i] 表示 源点 到i 当前 最短路径长度
d = [ 0 for i in range(len(node))]
shortestPath.dijkstra(node,connected,'V0',path,d)
if __name__=='__main__':
main()
结果截图: