主要思想
首先找到离源点最近的点,然后以这个点为源点再进行迭代,重复以上步骤
#-*- coding: utf-8 -*-
if __name__ =="__main__":
n=0
print("请输入图中点的数量")
n=input()
juzhen=[[0 for i in range(n)] for m in range(n)]
print("请依次输入矩阵")
for i in range(n):
for j in range(n):
juzhen[i][j]=input()
d=[0 for m in range(n)]#记录各个顶点到0的最短距离
p= [0 for m in range(n)]#记录最短路径要经过的点
use= [0 for m in range(n)]#记录是否已经求得最短路径
for i in range(n):
d[i]=0;
use[i]=0
p[i]=0
use[0]=1
for i in range(0,n):
d[i]=juzhen[0][i]#初始化d[i]的值
for i in range(1,n):
k=1
min=100000
for j in range(0,n):#首先找到目前最近的点
if (use[j]==0 and d[j]<min):
min=d[j]
k=j
use[k]=1
for w in range(0,n):#围绕这个点进行迭代
if(use[w]==0 and min+juzhen[k][w]<d[w]):
d[w]=min+juzhen[k][w]
p[w]=k
for i in range(0,n):
print(d[i])