狄杰斯特拉算法原理相信大家都很熟悉,这里再推荐一篇图片解释得很好的文章---文章
这篇文章是用java实现的,本文根据实际需求进行改善,主要区别为初始化输入是一个邻接矩阵。
废话不多说,直接上代码
- 案例一
A->B2->C1->D1->E2->F->14
- 案例二
B1->A->B2->C1->D1->E2->F->13
# 思路:动态规划
# 建立全点集,遍历过的标记为1,初始化为0
# 建立path集,在遍历的时候更新,初始化为列表,只放入源点
# 更新的逻辑:
# 1.每次找到当前源点到所有点的路径最短的那个点index,大for里面的第一个for
# 2.把这个点作为中介点,计算源点到中介点和其他点j的距离,大for里面的第二个for
# distance[source][index]+distance[index][j] 和 distance[source][j] 比较,如果小于则更新path集
# 3.更新点集
完整代码
def dijstra(d,dict1,visited,shortest,path,source,destiny):
dlen=len(d)
shortest[source]=0
visited[source]=1
for m in range(0,dlen):
dmin=99
dindex=-1
# 找每一次的当前源点到所有点的路径最短的那个点index
for x in range(0,dlen):
if( visited[x] == 0 and d[source][x] < dmin ):
dmin=d[source][x]
dindex=x
# 更新访问点
visited[dindex]=1
# 动态规划思想,转移公式:
# (源点到中介点距离D1+中介点到当前点距离D2)<(源点到当前点距离D3)时,把D3更新为D1+D2
for i in range(0,dlen):
if(visited[i] == 0 and (d[source][dindex]+d[dindex][i])<d[source][i] ):
d[source][i]=d[source][dindex]+d[dindex][i]
# 动态更新最短距离数值
shortest[i]=d[source][i]
# 动态更新最短路径
path[i]=[i for i in path[dindex]]+[i]
# 输出结果
printLast(path,dict1,shortest)
def printLast(path,dict1,shortest):
for i in path[-1]:
print(dict1[i+1]+"->",end="")
print(shortest[-1])
def runDi(d1,dict1,source,destiny):
# 初始化
visited=[]
shortest=[]
path=[]
for i in range(0,len(d)):
visited.append(0)
shortest.append(0)
# 路径初始化为源点到各个点
path.append([source,i])
dijstra(d1,dict1,visited,shortest,path,source,destiny)
初始化及运行
d = [[0,3,5,4,99,99,99,99,99,99,99,99,99],
[99,0,99,99,9,5,99,99,99,99,99,99,99],
[99,99,0,99,4,3,5,99,99,99,99,99,99],
[99,99,99,0,99,1,7,99,99,99,99,99,99],
[99,99,99,99,0,99,99,1,5,99,99,99,99],
[99,99,99,99,99,0,99,8,4,6,99,99,99],
[99,99,99,99,99,99,0,4,4,2,99,99,99],
[99,99,99,99,99,99,99,0,99,99,4,2,99],
[99,99,99,99,99,99,99,99,0,99,6,9,99],
[99,99,99,99,99,99,99,99,99,0,7,5,99],
[99,99,99,99,99,99,99,99,99,99,0,99,1],
[99,99,99,99,99,99,99,99,99,99,99,0,2],
[99,99,99,99,99,99,99,99,99,99,99,99,0]]
d1 = [[0,99,1,4,99,99,99,99,99,99,99,99,99],
[3,0,99,99,9,6,99,99,99,99,99,99,99],
[99,99,0,99,4,1,5,99,99,99,99,99,99],
[99,99,99,0,99,1,7,99,99,99,99,99,99],
[99,99,99,99,0,99,99,1,5,99,99,99,99],
[99,99,99,99,99,0,99,8,4,6,99,99,99],
[99,99,99,99,99,99,0,4,4,2,99,99,99],
[99,99,99,99,99,99,99,0,99,99,4,2,99],
[99,99,99,99,99,99,99,99,0,99,6,9,99],
[99,99,99,99,99,99,99,99,99,0,7,5,99],
[99,99,99,99,99,99,99,99,99,99,0,99,1],
[99,99,99,99,99,99,99,99,99,99,99,0,2],
[99,99,99,99,99,99,99,99,99,99,99,99,0]]
dict1 = {1 : 'A',2 : 'B1',3 : 'B2',4 : 'B3',5 : 'C1',6 : 'C2',7 : 'C3',8 : 'D1',9 : 'D2',10 : 'D3',11 : 'E1',12 : 'E2',13 : 'F'}
runDi(d,dict1,0,12)
runDi(d1,dict1,1,12)
输出结果
A->B2->C1->D1->E2->F->14 B1->A->B2->C1->D1->E2->F->13