#_*_coding=utf-8_*_import numpy as np
maxNum=1000000#用一个大数表示无穷大defDijkstra(G,S):
nV=len(G[0])
#初始化顶点访问标签
label=np.array([False]*nV)
label[S]=True#初始化距离向量
Dis=np.array([maxNum]*5)
for i in range(nV):
Dis[i]=G[S][i]
Dis[S]=0for i in range(nV):
u=minDis(G,label,Dis)
if u==nV:
breakif Dis[u]==maxNum:
continue
label[u]=Truefor j in range(5):
if G[u][j]!=maxNum and Dis[j]>(Dis[u]+G[u][j]):
Dis[j]=Dis[u]+G[u][j]
return Dis
defminDis(G,label,Dis):
u=0
nV=len(G[0])
#顺序查找第一个未访问顶点,全部访问则返回nVwhile(u<nV and label[u]):
u+=1#查找距离更小的未访问结点
l=range(u+1,nV,1)
for i in l:
ifnot label[i] and Dis[i]<Dis[u]:
u=i
return u
G=np.array([[maxNum,7,6,maxNum,maxNum],
[7,maxNum,maxNum,3,4],
[6,maxNum,maxNum,maxNum,2],
[maxNum,3,maxNum,maxNum,1],
[maxNum,4,2,1,maxNum]])
for i in range(len(G[0])):
print Dijkstra(G,i)
>>>
=============== RESTART: E:\DS&A\算法实现\Dijkstra\Dijkstra.py ===============
[07698]
[70634]
[66032]
[93301]
[84210]