美文网首页大数据 爬虫Python AI SqlPython小哥哥
从无名小村落到长春最快多长时间?用Python实现狄克斯特拉算法

从无名小村落到长春最快多长时间?用Python实现狄克斯特拉算法

作者: 14e61d025165 | 来源:发表于2019-05-26 14:37 被阅读1次

狄克斯特拉算法介绍

Dijkstra(迪杰斯特拉)算法是典型的单源最短路径算法,用于计算一个节点到其他所有节点的最短路径。主要特点是以起始点为中心向外层层扩展,直到扩展到终点为止。Dijkstra算法是很有代表性的最短路径算法,在很多专业课程中都作为基本内容有详细的介绍,如数据结构,图论,运筹学等等。注意该算法要求图中不存在负权边。

问题描述:在无向图 G=(V,E) 中,假设每条边 E[i] 的长度为 w[i],找到由顶点 V0 到其余各点的最短路径。(单源最短路径)

2.算法描述

Python学习交流群:1004391443,这里有资源共享,技术解答,还有小编从最基础的Python资料到项目实战的学习资料都有整理,希望能帮助你更了解python,学习python

(1)算法思想:设G=(V,E)是一个带权有向图,把图中顶点集合V分成两组,第一组为已求出最短路径的顶点集合(用S表示,初始时S中只有一个源点,以后每求得一条最短路径 , 就将加入到集合S中,直到全部顶点都加入到S中,算法就结束了),第二组为其余未确定最短路径的顶点集合(用U表示),按最短路径长度的递增次序依次把第二组的顶点加入S中。在加入的过程中,总保持从源点v到S中各顶点的最短路径长度不大于从源点v到U中任何顶点的最短路径长度。此外,每个顶点对应一个距离,S中的顶点的距离就是从v到此顶点的最短路径长度,U中的顶点的距离,是从v到此顶点只包括S中的顶点为中间顶点的当前最短路径长度。

(2)算法步骤:

a.初始时,S只包含源点,即S={v},v的距离为0。U包含除v外的其他顶点,即:U={其余顶点},若v与U中顶点u有边,则<u,v>正常有权值,若u不是v的出边邻接点,则<u,v>权值为∞。

b.从U中选取一个距离v最小的顶点k,把k,加入S中(该选定的距离就是v到k的最短路径长度)。

c.以k为新考虑的中间点,修改U中各顶点的距离;若从源点v到顶点u的距离(经过顶点k)比原来距离(不经过顶点k)短,则修改顶点u的距离值,修改后的距离值的顶点k的距离加上边上的权。

d.重复步骤b和c直到所有顶点都包含在S中。

引用自[ 最短路径—Dijkstra算法和Floyd算法 ]

我的解释

其实没有这么难,对于我来说,只有这几步:

找出最快能到达的节点。

更新它邻居的开销。

重复,再重复。

直到没有未处理的节点。

感觉被世界上最恶毒的小编耍了 别走! 后面有料!没有高铁的春运难题

一个人,去一个农家乐旅游,想要回到家乡长春,应该怎么回去?

那个人画了这张图:

<tt-image data-tteditor-tag="tteditorTag" contenteditable="false" class="syl1558852584254" data-render-status="finished" data-syl-blot="image" style="box-sizing: border-box; cursor: text; color: rgb(34, 34, 34); font-family: "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", "WenQuanYi Micro Hei", "Helvetica Neue", Arial, sans-serif; font-size: 16px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: left; text-indent: 0px; text-transform: none; white-space: pre-wrap; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; background-color: rgb(255, 255, 255); text-decoration-style: initial; text-decoration-color: initial; display: block;"> image

<input class="pgc-img-caption-ipt" placeholder="图片描述(最多50字)" value="" style="box-sizing: border-box; outline: 0px; color: rgb(102, 102, 102); position: absolute; left: 187.5px; transform: translateX(-50%); padding: 6px 7px; max-width: 100%; width: 375px; text-align: center; cursor: text; font-size: 12px; line-height: 1.5; background-color: rgb(255, 255, 255); background-image: none; border: 0px solid rgb(217, 217, 217); border-radius: 4px; transition: all 0.2s cubic-bezier(0.645, 0.045, 0.355, 1) 0s;"></tt-image>

image

图上 意思 它是什么? 数字 时间 权重 点 城市 节点 箭头 方向 边(有向) 转换为 dict

<pre spellcheck="false" style="box-sizing: border-box; margin: 5px 0px; padding: 5px 10px; border: 0px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-variant-numeric: inherit; font-variant-east-asian: inherit; font-weight: 400; font-stretch: inherit; font-size: 16px; line-height: inherit; font-family: inherit; vertical-align: baseline; cursor: text; counter-reset: list-1 0 list-2 0 list-3 0 list-4 0 list-5 0 list-6 0 list-7 0 list-8 0 list-9 0; background-color: rgb(240, 240, 240); border-radius: 3px; white-space: pre-wrap; color: rgb(34, 34, 34); letter-spacing: normal; orphans: 2; text-align: left; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">graph = {
'start.': {'Beijing': 5, 'TrainStation': 0, },
'Beijing': {'ShanHaiGuan': 15, 'ShenYang': 20, },
'ShanHaiGuan': {'ChangChun': 20, },
'TrainStation': {'ShanHaiGuan': 30, 'ShenYang': 35, },
'ShenYang': {'ChangChun': 10, },
'ChangChun': None,
}
</pre>

用来存储父节点和花销的散列表类似于这样:

<pre spellcheck="false" style="box-sizing: border-box; margin: 5px 0px; padding: 5px 10px; border: 0px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-variant-numeric: inherit; font-variant-east-asian: inherit; font-weight: 400; font-stretch: inherit; font-size: 16px; line-height: inherit; font-family: inherit; vertical-align: baseline; cursor: text; counter-reset: list-1 0 list-2 0 list-3 0 list-4 0 list-5 0 list-6 0 list-7 0 list-8 0 list-9 0; background-color: rgb(240, 240, 240); border-radius: 3px; white-space: pre-wrap; color: rgb(34, 34, 34); letter-spacing: normal; orphans: 2; text-align: left; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">costs = {
'Beijing': 5,
'ShanHaiGuan': float('inf'),
'TrainStation': 0,
'ShenYang': float('inf'),
'ChangChun': float('inf'),
}
parents = {
'Beijing': 'start.',
'ShanHaiGuan': None,
'TrainStation': 'start.',
'ShenYang': None,
'ChangChun': None,
}
</pre>

这只是为了方便让您看懂。 costs 和 parents 散列表( dict )无需手动实现,下面会告诉您如何自动根据 graph 生成对应的初始化的 costs 和 parents 。

Let's GO!

算法实现:

<pre spellcheck="false" style="box-sizing: border-box; margin: 5px 0px; padding: 5px 10px; border: 0px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-variant-numeric: inherit; font-variant-east-asian: inherit; font-weight: 400; font-stretch: inherit; font-size: 16px; line-height: inherit; font-family: inherit; vertical-align: baseline; cursor: text; counter-reset: list-1 0 list-2 0 list-3 0 list-4 0 list-5 0 list-6 0 list-7 0 list-8 0 list-9 0; background-color: rgb(240, 240, 240); border-radius: 3px; white-space: pre-wrap; color: rgb(34, 34, 34); letter-spacing: normal; orphans: 2; text-align: left; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">def find_quickest_way(graph, start, finish):
# 根据图生成花销表
costs = {}
for k, v in graph.items():
using_parents = graph[start]
costs.update(using_parents)
if k != start:
if k not in using_parents.keys():
costs[k] = float('inf')
# 生成初始父节点表
parents = {}
for k, v in costs.items():
if v == float('inf'):
parents[k] = None
else:
parents[k] = start
# 用来存储处理过的节点
processed = []
# 最近的节点
node = find_nearest_station(costs, processed)
# 开始狄克斯特拉算法
while node is not None:
# 如果最快的点是终点,则表明算法结束了
if node == finish:
break
# 通向这个节点的花销
cost = costs[node]
# 所有可以连接到的点
neighbours = graph[node]
for t, c in neighbours.items():
# 新的花销
new_cost = cost + c
# 如果花销更小,使它的这个邻居成为子节点
if new_cost < costs[t]:
costs[t] = new_cost
parents[t] = node
# 处理过了
processed.append(node)
# 最近的节点
node = find_nearest_station(costs, processed)
# 返回子父节点表
return parents
def find_nearest_station(costs, processed):
"""傻瓜算法, 找到最快速的节点"""
lowest_cost = float('inf')
lowest_node = None
for k in costs.keys():
if costs[k] < lowest_cost and k not in processed:
lowest_cost = costs[k]
lowest_node = k
return lowest_node
</pre>

测试一下!

小编最近整理了一套Python学习教程,有需要的小伙伴,记得来小编的交流群:729720844,即可免费领取一套Python学习教程哦

<pre spellcheck="false" style="box-sizing: border-box; margin: 5px 0px; padding: 5px 10px; border: 0px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-variant-numeric: inherit; font-variant-east-asian: inherit; font-weight: 400; font-stretch: inherit; font-size: 16px; line-height: inherit; font-family: inherit; vertical-align: baseline; cursor: text; counter-reset: list-1 0 list-2 0 list-3 0 list-4 0 list-5 0 list-6 0 list-7 0 list-8 0 list-9 0; background-color: rgb(240, 240, 240); border-radius: 3px; white-space: pre-wrap; color: rgb(34, 34, 34); letter-spacing: normal; orphans: 2; text-align: left; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">line = ['ChangChun']

graph散列表见上文“没有高铁的春运难题:转换为dict”

my_parents = find_quickest_way(graph, 'start.', 'ChangChun')
while True:
parent = my_parents[line[0]]
line.insert(0, parent)
if parent == 'start.':
break
print(*line, sep=' => ')
start. => Beijing => ShenYang => ChangChun
Process finished with exit code 0
</pre>

成功!

还记得 最短路径—Dijkstra算法和Floyd算法 这个文章吗?在开头提到过。这里面还有一个很好用的算法Floyd算法。

相关文章

网友评论

    本文标题:从无名小村落到长春最快多长时间?用Python实现狄克斯特拉算法

    本文链接:https://www.haomeiwen.com/subject/zuoxtctx.html