#-*- coding: cp936 -*- -*-
from sys import maxint
class shortestPath:
@staticmethod
def floyd(node,connected,path):
for i in range(len(node)):
for j in range(len(node)):
if connected[i][j]<maxint:
path[i][j][i]=True
path[i][j][j]=True
for u in range(len(node)):#中间顶点的序号从 0 到 n-1
for v in range(len(node)):
for w in range(len(node)):
if connected[v][u]+connected[u][w] < connected[v][w]:
connected[v][w]=connected[v][u]+connected[u][w]
for t in range(len(node)):
path[v][w][t] = path[v][u][t] or path[u][w][t]
shortestPath.printPath(node,connected,path)
@staticmethod
def printPath(node,connected,path):
for i in range(len(node)):
for j in range(len(node)):
if i == j:
continue
print("------------------------")
throughNode=[]
for t in range(len(node)):
if path[i][j][t]:
throughNode.append((connected[i][t],t))
throughNode.sort(key=lambda tup:tup[0])
if connected[i][j]==maxint:
print(node[i]+" and "+node[j]+" not connected")
else:
print(node[i]+"->"+node[j]+" cost "+str(connected[i][j]))
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][k]为True表示 k 是 i到j 当前最短路径 的一个点
path = [[[False for i in range(len(node))] for j in range(len(node))] for k in range(len(node))]
shortestPath.floyd(node,connected,path)
if __name__=='__main__':
main()
结果截图: