python求最短路径的方法_python --Dijkstra 算法求取最短路径

#大名鼎鼎的Dijkstra是一种广度优先算法:

#!/usr/bin/env python3

# -*- coding: utf-8 -*-

import numbers

import numpy

import math

'''

Dijkstra 算法说明

初始条件:

1、设定邻接列表或邻接矩阵

2、选定初始节点

3、设立已确立最短线路的节点集,包括目标节点标志、路径权重、路径节点序列(set1)

4、设立待优化路径集合,包裹目标节点标志、路径权重、路径节点序列(set2)

5、当前节点

*********************************

方法:

1、选定节点该,直接进入set1

2、当前节点不包含于set1的邻接节点,并累计到这些这些节点的权重的到临时settemp;

3、settemp中的元素逐个与set2中的待优化路径比较:目标节点相同则相比较区中,set中的做选择权重小的路径;未有匹配的路径则直接写入(松弛)

4、在set2中选择权重最小的节点写入set1,并将这个节点作为当前节点

5、重复2-4部

#代码:

def dijkstra(curp,setf,nfix):

setf[curp[-1][0]]=[curp[-1][1],curp[-1][2]]

temppoint = ''

temppath = ''

tempright = 0

for i in adjoin:

if i[0] ==curp[0][0] and i[1] not in setf:

temppoint=i[1]

temppath=curp[0][1]+i[1]

tempright=i[2]+curp[0][2]

else:

if i[1]==curp[0][0] and i[0] not in setf:

temppoint = i[0]

temppath = curp[0][1] + i[0]

tempright = i[2] + curp[0][2]

else:temppoint=None

if temppoint!=None:

if temppoint not in nfix:

nfix[temppoint]=[temppath,tempright]

else:

if nfix[temppoint][1]>tempright:

nfix[temppoint]=[temppath,tempright]

curp.clear()

curp.append(['','',1000])

for key in nfix:

if nfix[key][1]

curp.clear()

curp.append([key,nfix[key][0],nfix[key][1]])

setf[curp[-1][0]]=[curp[-1][1],curp[-1][2]]

del nfix[curp[-1][0]]

if nfix :

dijkstra(curp,setf,nfix)

else:

print(setf)

#用例

adjoin=[]

adjoin.append(['A','B',10])

adjoin.append(['A','F',11])

adjoin.append(['B','G',16])

adjoin.append(['B','C',18])

adjoin.append(['B','I',12])

adjoin.append(['C','I',8])

adjoin.append(['C','D',22])

adjoin.append(['D','I',21])

adjoin.append(['D','H',16])

adjoin.append(['D','E',20])

adjoin.append(['D','G',24])

adjoin.append(['E','F',26])

adjoin.append(['F','G',17])

adjoin.append(['G','H',19])

startpoint='A'

currentpoint=[['B','B',0]]

setfixed={}#setfixed{}={'B':['AB',10]}

needfix={}#与setfixed[0]相同

dijkstra(currentpoint,setfixed,needfix)

#输出:

{'B': ['B', 0], 'A': ['BA', 10], 'I': ['BI', 12], 'G': ['BG', 16], 'C': ['BC', 18], 'F': ['BAF', 21], 'D': ['BID', 33], 'H': ['BGH', 35], 'E': ['BAFE', 47]}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值