Floyd算法

#-*- 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()

结果截图:



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值