December 18, 2015 12:56 PM
Dijkstra(迪杰斯特拉)算法是典型的最短路径算法,用于计算一个节点到其他所有节点的最短路径。主要特点是以起始点为中心向外层层扩展,直到扩展到终点为止。Dijkstra算法能得出最短路径的最优解,但由于它遍历计算的节点很多,所以效率低。
Dijkstra算法是很有代表性的最短路算法,在很多专业课程中都作为基本内容有详细的介绍,如数据结构,图论,运筹学等等。
其基本思想是,设置顶点集合S并不断地作贪心选择来扩充这个集合。一个顶点属于集合S当且仅当从源到该顶点的最短路径长度已知。
初始时,S中仅含有源。设u是G的某一个顶点,把从源到u且中间只经过S中顶点的路称为从源到u的特殊路径,并用数组dist记录当前每个顶点所对应的最短特殊路径长度。Dijkstra算法每次从V-S中取出具有最短特殊路长度的顶点u,将u添加到S中,同时对数组dist作必要的修改。一旦S包含了所有V中顶点,dist就记录了从源到所有其它顶点之间的最短路径长度。
#Dijkstra.py
#王渊
#2015.12.17
#Email:wyxidian@gmail.com
from pylab import *
INFINITY = 65535 #代表无穷大
vexs = array([[0,10,INFINITY,INFINITY,INFINITY,11,INFINITY,INFINITY,INFINITY],#邻接矩阵
[10,0,18,INFINITY,INFINITY,INFINITY,16,INFINITY,12],
[INFINITY,18,0,22,INFINITY,INFINITY,INFINITY,INFINITY,8],
[INFINITY,INFINITY,22,0,20,INFINITY,INFINITY,16,21],
[INFINITY,INFINITY,INFINITY,20,0,26,INFINITY,7,INFINITY],
[11,INFINITY,INFINITY,INFINITY,26,0,17,INFINITY,INFINITY],
[INFINITY,16,INFINITY,24,INFINITY,17,0,19,INFINITY],
[INFINITY,INFINITY,INFINITY,16,7,INFINITY,19,0,INFINITY],
[INFINITY,12,8,21,INFINITY,INFINITY,INFINITY,INFINITY,0]])
lengthVex = len(vexs) #邻接矩阵大小
adjvex = zeros(lengthVex) #连通分量,初始只有第一个顶点,当全部元素为1后,说明连通分量已经包含所有顶点
adjvex[0] = 1;
lowCost = vexs[0,:] #记录与连通分量连接的顶点的最小权值,初始化为与第一个顶点连接的顶点权值
lowCost[0] = 0
lastLowCost = ones(lengthVex)*INFINITY
lastLowCost[0] = 0
count = 0
path = [INFINITY]*lengthVex
I = 0
while (count<lengthVex):
lastI = I
I = (argsort(lowCost))[count]
print("Vertex [",count,"]:",I)
adjvex[I] = lowCost[I]
print("Edge [",count,"]:",adjvex[I])
lowCost = array(list(map(lambda x,y:x if x<y else y,lowCost,vexs[I,:])))
flag = list(map(lambda x,y: x==y, lowCost,lastLowCost))
flag[I] = True
print(flag)
path = list(map(lambda x,y,z:y if x else z,flag,path,list([I])*lengthVex))
print(path)
lastLowCost = lowCost
count = count+1
minPath = []
temp = 4
while path[temp]<INFINITY:
minPath.append([temp,path[temp]])
temp = path[temp]
print(minPath)
最后给出两道题目练手,都是直接套用模版就OK的:
1.HDOJ 1874 畅通工程续
http://www.wutianqi.com/?p=1894
2.HDOJ 2544 最短路
http://www.wutianqi.com/?p=1892