最短路径问题的Dijkstra算法

是由荷兰计算机科学家艾兹赫尔·戴克斯特拉提出。迪科斯彻算法使用了广度优先搜索解决非负权有向图的单源最短路径问题,算法最终得到一个最短路径树>    。该算法常用于路由算法或者作为其他图算法的一个子模块。

# Dijkstra's algorithm for shortest paths

# David Eppstein, UC Irvine, 4 April 2002

# http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/117228

from priodict import priorityDictionary

def Dijkstra(G,start,end=None):

"""

Find shortest paths from the start vertex to all vertices nearer than or equal to the end.

The input graph G is assumed to have the following representation:

A vertex can be any object that can be used as an index into a dictionary.

G is a dictionary, indexed by vertices. For any vertex v, G[v] is itself a dictionary,

indexed by the neighbors of v. For any edge v->w, G[v][w] is the length of the edge.

This is related to the representation in

where Guido van Rossum suggests representing graphs as dictionaries mapping vertices

to lists of outgoing edges, however dictionaries of edges have many advantages over lists:

they can store extra information (here, the lengths), they support fast existence tests,

and they allow easy modification of the graph structure by edge insertion and removal.

Such modifications are not needed here but are important in many other graph algorithms.

Since dictionaries obey iterator protocol, a graph represented as described here could

be handed without modification to an algorithm expecting Guido's graph representation.

Of course, G and G[v] need not be actual Python dict objects, they can be any other

type of object that obeys dict protocol, for instance one could use a wrapper in which vertices

are URLs of web pages and a call to G[v] loads the web page and finds its outgoing links.

The output is a pair (D,P) where D[v] is the distance from start to v and P[v] is the

predecessor of v along the shortest path from s to v.

Dijkstra's algorithm is only guaranteed to work correctly when all edge lengths are positive.

This code does not verify this property for all edges (only the edges examined until the end

vertex is reached), but will correctly compute shortest paths even for some graphs with negative

edges, and will raise an exception if it discovers that a negative edge has caused it to make a mistake.

"""

D = {}# dictionary of final distances

P = {}# dictionary of predecessors

Q = priorityDictionary()# estimated distances of non-final vertices

Q[start] = 0

for v in Q:

D[v] = Q[v]

if v == end: break

for w in G[v]:

vwLength = D[v] + G[v][w]

if w in D:

if vwLength < D[w]:

raise ValueError, "Dijkstra: found better path to already-final vertex"

elif w not in Q or vwLength < Q[w]:

Q[w] = vwLength

P[w] = v

return (D,P)

def shortestPath(G,start,end):

"""

Find a single shortest path from the given start vertex to the given end vertex.

The input has the same conventions as Dijkstra().

The output is a list of the vertices in order along the shortest path.

"""

D,P = Dijkstra(G,start,end)

Path = []

while 1:

Path.append(end)

if end == start: break

end = P[end]

Path.reverse()

return Path

# example, CLR p.528

G = {'s': {'u':10, 'x':5},

'u': {'v':1, 'x':2},

'v': {'y':4},

'x':{'u':3,'v':9,'y':2},

'y':{'s':7,'v':6}}

print Dijkstra(G,'s')

print shortestPath(G,'s','v')

标签 :tech

IT瘾于2014年6月22日 上午01时16分00秒发布

#

python广度优先算法最短路径_最短路径问题的Dijkstra算法 -python相关推荐

  1. 数据结构_图_最短路径_狄杰斯特拉(Dijkstra)算法

    此算法没有采用<数据结构C语言版>中的存储结构,而是采用邻接表的方法存储图,经过改进,还能输出最短路径. "Dijkstra.h" #include<iostre ...

  2. java dijkstra算法代码_[转载]Java实现dijkstra算法: 地图中任意起点寻找最佳路径...

    最近在复习java,下学期要用,写这个练手.  技术较粗糙,见谅. 代码里用的是这幅地图,根据实际情况更改,在addNode方法中 这个是运行结果,起点和终点在 运行wrap(String qidia ...

  3. 网上路径的图片有时候遍历不出来_最短路径问题(1)——Dijkstra算法

    找到距离集合Q最近的点B,将其加入集合Q中,并从P中删除,遍历与B相邻的点.由数组N可知A->B=5,B->D=5,所以A->B+B->D = 10,小于原本A->D的距 ...

  4. (单源最短路径)一文搞懂dijkstra算法

    前言 大家好,我是bigsai,今天给大家讲讲Dijkstra算法,下次拿着这个算法找女神少绕路,有女朋友的可以试试行不行的通. 对于Dijkstra算法,很多人可能感觉熟悉而又陌生,可能大部分人比较 ...

  5. 经典算法研究系列:二、Dijkstra 算法初探

    经典算法研究系列:二.Dijkstra 算法初探  July   二零一一年一月 ====================== 本文主要参考:算法导论 第二版.维基百科. 写的不好之处,还望见谅. 本 ...

  6. dijkstra最短路径算法视频_单源最短路径(1):Dijkstra 算法

    一:背景 Dijkstra 算法(中文名:迪杰斯特拉算法)是由荷兰计算机科学家 Edsger Wybe Dijkstra 提出.该算法常用于路由算法或者作为其他图算法的一个子模块.举例来说,如果图中的 ...

  7. 贪心算法单源点最短路径例题c语言源代码,Dijkstra算法是解单源最短路径问题的一个贪心算法...

    问题描述 给定一个带权有向图 G=(V,E) ,其中每条边的权是一个非负实数. 另外,还给定 V 中的一个项点,称为源. 现在我们要计算从源到所有其他各项点的最短路径长度. 这里的长度是指路上各边权之 ...

  8. 数据结构与算法(7-4)最短路径(迪杰斯特拉(Dijkstra)算法、弗洛伊德(Floyd)算法)

    目录 一.最短路径概念 二.迪杰斯特拉(Dijkstra)算法(单源最短路径) 1.原理 2.过程 3.代码 三.弗洛伊德(Floyd)算法(多源最短路径) 1.原理 2.存储 3.遍历 4.代码 参 ...

  9. 单源最短路径(1):Dijkstra算法

    原文: https://subetter.com/algorith... 一:背景 Dijkstra算法(中文名:迪杰斯特拉算法)是由荷兰计算机科学家Edsger Wybe Dijkstra提出.该算 ...

最新文章

  1. 中序非递归遍历二叉树
  2. 资源 | 5月Python好文TOP 10新鲜出炉,你都看了吗?
  3. es文件浏览器鸿蒙,手机文件一团糟 八款安卓文件管理器来救急
  4. 北邮OJ 981. 16校赛-Saber's Number Game
  5. 一行上自动控制数据长度,并换行
  6. 华为鲲鹏弹性云服务器KM1_#化鲲为鹏,我有话说# 鲲鹏弹性云服务器配置 Tomcat...
  7. Fixed Function Shader
  8. 【Elasticsearch】elasticsearch bool 布尔 查询
  9. Java设计模式透析之 —— 适配器(Adapter)
  10. jsp下Kindeditor环境搭建
  11. latex中Winedt和Sumatra PDF互联设置及失效解决
  12. MySQL学习笔记第8课(共10课)
  13. OpenCV开发笔记(六十七):红胖子8分钟带你深入了解特征点暴力匹配(图文并茂+浅显易懂+程序源码)
  14. 数据科学的原理与技巧 四、数据清理
  15. iOS开发-Please sign in with an app-specific password. You can create one at appleid.apple.com
  16. linux 误删除根分区的pv,如何安全的删除Linux LVM中的PV物理卷(硬盘或分区)(4)
  17. 全栈工程师的百宝箱:黑魔法之文档篇
  18. Win10系统安装CUDA10.0和cuDNN
  19. IPv6和IPv4的区别
  20. leetcode 1641. Count Sorted Vowel Strings(python)

热门文章

  1. 机器学习入门(三):神经网络起手式
  2. 自定义binder架构的 client/ server组件
  3. Android 关机流程 从kernel到framework
  4. 5年IT从业的感悟和未来百万年薪畅想
  5. 成人教育计算机教育论文,【计算机教育论文】成人计算机教育应把握原则(共3460字)...
  6. linux 计时程序,Linux下使用clock_gettime给程序计时
  7. 盐城计算机考试时间安排,2019盐城中考具体时间安排 什么时候考试
  8. ffmpeg 截图太模糊了_技法课堂 | 巧用截图工具,一小时迅速完成线稿风效果图...
  9. java .class 实例对象_Java产生Class类的三种实例化对象的方法
  10. vba 字体颜色_Excel填充单元格颜色和改变字体颜色,用VBA是怎样实现的呢?