#_*_coding=utf-8_*_
import numpy as np
maxNum=1000000 #用一个大数表示无穷大
def Dijkstra(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]=0
for i in range(nV):
u=minDis(G,label,Dis)
if u==nV:
break
if Dis[u]==maxNum:
continue
label[u]=True
for 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
def minDis(G,label,Dis):
u=0
nV=len(G[0])
#顺序查找第一个未访问顶点,全部访问则返回nV
while(u<nV and label[u]):
u+=1
#查找距离更小的未访问结点
l=range(u+1,nV,1)
for i in l:
if not 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 ===============
[0 7 6 9 8]
[7 0 6 3 4]
[6 6 0 3 2]
[9 3 3 0 1]
[8 4 2 1 0]
Dijkstra算法的Python实现
最新推荐文章于 2024-04-12 15:55:24 发布