迪杰斯特拉算法
def myDijkstra ( statr: int , lst: list ) :
"""
:param statr: 开始的地点
:param lst: 各个城市之间的距离, 二维数组,就是用行列坐标表示图形上两点之间的距离。
:return: 到各个城市的最短距离
"""
city = [ x for x in range ( len ( lst) ) if x != statr]
cityorder = [ statr]
citylength = lst[ statr]
while len ( city) :
idenx1 = city[ 0 ]
for i in city:
if citylength[ i] < citylength[ idenx1] :
idenx1 = i
city. remove( idenx1)
cityorder. append( idenx1)
for i in city:
if citylength[ idenx1] + lst[ idenx1] [ i] < citylength[ i] :
citylength[ i] = citylength[ idenx1] + lst[ idenx1] [ i]
return citylength
if __name__ == '__main__' :
max = 999999
graph = [
[ 5 , max , 10 , max , 30 , 100 ] ,
[ max , max , 5 , max , max , max ] ,
[ max , 15 , max , 50 , max , max ] ,
[ max , max , max , max , max , 10 ] ,
[ max , max , max , 20 , max , 60 ] ,
[ max , 15 , max , max , max , max ] ,
]
inf = 999999
mgraph = [ [ 0 , 1 , 12 , inf, inf, inf] ,
[ inf, 0 , 9 , 3 , inf, inf] ,
[ inf, inf, 0 , inf, 5 , inf] ,
[ inf, inf, 4 , 0 , 13 , 15 ] ,
[ inf, inf, inf, inf, 0 , 4 ] ,
[ inf, inf, inf, inf, inf, 0 ] ]
len1 = myDijkstra( 0 , graph)
print ( len1)
len2 = myDijkstra( 0 , mgraph)
print ( len2)