algorithms-ch4-paths in graphs

4.1 Distane

The distance between two nodes is the length of the shortest path between them.

4.2 Breadth-first search

All the breadth-first search tree's paths from S are the shortest possible. It is therefore a shortest-path tree.

procedure bfs(G,s)
Input: Graph G = (V,E), directed or undirected; vertex s ∈ V
Output: For all vertices u reachable from s, dist(u) is set to the distance from s to u.

for all u ∈ V :
  dist(u) = ∞

dist(s) = 0
Q = [s] (queue containing just s)
while Q is not empty:
  u = eject(Q)
  for all edges (u, v) ∈ E:
    if dist(v) = ∞:
      inject(Q, v)
       dist(v) = dist(u) + 1

The overall running time of this algorithm is linear, O(|V | + |E|)

comparison DFS BFS
search strategy Depth-first search makes deep incursions into a graph, retreating only when it runs out of new nodes to visit Breadth-first search makes sure to visit vertices in increasing order of their distance from the starting point.
implementation stack queue
application cycle test, connection test, SCC(directed) ,topological sort cycle test, connection test, shortest path
time complexity adjacent matrix Θ(V^2), adjacent list Θ(V+E) same as DFS
// Θ( V + E )

4.4 Dijkstra’s algorithm

知乎上看到过一篇文章介绍Dijkstra,有兴趣可。(非广告,无广告费。。)

procedure dijkstra(G, l, s)
Input: Graph G = (V, E), directed or undirected;positive edge lengths {le : e ∈ E}; vertex s ∈ V
Output:For all vertices u reachable from s, dist(u) is setto the distance from s to u.

for all u ∈ V :
  dist(u) = ∞
  prev(u) = nil

dist(s) = 0

H = makequeue (V ) (using dist-values as keys)
while H is not empty:
  u = deletemin(H )
  for all edges (u, v) ∈ E:
    if dist(v) > dist(u) + l(u, v):
      dist(v) = dist(u) + l(u, v)
      prev(v) = u  //shortest path 
      decreasekey(H, v) // decrease the key( value of dist(v)) in the queue
Running time

Dijkstra’s algorithm is structurally identical to breadth-first search. However, it is slower because the priority queue primitives are computationally more demanding than the constant-time eject’s and inject’s of BFS

we get a total of |V | deletemin and |V | + |E| insert/decreasekey operations.

Paste_Image.png

4.5 Priority queue implementations

4.5.1 Array

The simplest implementation of a priority queue is as an unordered array of key values for all potential elements (the vertices of the graph, in the case of Dijkstra’s algorithm). Initially,these values are set to ∞.

An insert or decreasekey is fast, because it just involves adjusting a key value, an O(1) operation. To deletemin, on the other hand, requires a linear-time scan of the list.

4.5.2 Binary heap
  1. Elements are stored in a complete binary tree
  2. each level is filled in from left to right, and must be full before the next level is started.
  3. the key value of any node of the tree is less than or equal to that of its children.

Therefore, the root always contains the smallest element.

  • To insert, place the new element at the bottom of the tree (in the first available position),and let it “bubble up.”(if it is smaller than its parent, swap the two and repeat)The number of swaps is at most the height of the tree, which is ⌊log2 n⌋when there are n elements
  • To deletemin, take the last node in the tree and place it at the root.Let it “sift down”.(if it is bigger than either child, swap it with the smaller child and repeat)Again this takes O(log n) time.
4.5.3 d-ary heap

A d-ary heap is identical to a binary heap, except that nodes have d children instead of justtwo. This reduces the height of a tree with n elements to Θ(logd n) = Θ((log n)/(log d)). Insertsare therefore speeded up by a factor of Θ(log d). Deletemin operations, however, take a littlelonger, namely O(d logd n)

4.6 Shortest paths in the presence of negative edges

Bellman-ford algorithm

procedure update((u, v) ∈ E)
dist(v) = min{dist(v), dist(u) + l(u, v)}

procedure shortest-paths(G, l, s)
Input: Directed graph G = (V, E);edge lengths {le : e ∈ E} with no negative cycles;vertex s ∈ V
Output: For all vertices u reachable from s, dist(u) is set to the distance from s to u.

for all u ∈ V :
  dist(u) = ∞
  prev(u) = nil

dist(s) = 0
repeat |V | − 1 times:
  for all e∈E:
    update(e)

具体是:

graph
more specific
Negative cycles

The shortest-path problem is ill-posed in graphs with negative cycles.
Such acycle would allow us to endlessly apply rounds of update operations, reducing dist estimates every time.
There is a negative cycle if and only if some dist value is reduced during this final round.

4.7 Shortest paths in dags

DAGs avoid negative cycle.

procedure dag-shortest-paths(G, l, s)
Input: DagG=(V,E);edge lengths {le :e∈E};vertex s∈V
Output: For all vertices u reachable from s, dist(u) is set to the distance from s to u.

for all u ∈ V :
  dist(u) = ∞
  prev(u) = nil

dist(s) = 0
Linearize G
for each u ∈ V , in linearized order:
  for all edges (u, v) ∈ E:
    update(u, v)

procedure update((u, v) ∈ E)
dist(v) = min{dist(v), dist(u) + l(u, v)}

In particular, we can find longest paths in a dag by the same algorithm: just negate all edge lengths.

To sum up all algorithms for shortest path:

Algorithms features Time complexity
BFS s->t, weight=1 O(|V|+|E|)
dijkstra s->t, non-negative weight binary heap:O((|V|+|E|)*log|V|)
Bellman-ford s->t, can deal with negative weight O(|V|*|E|)
DAG s->t, DAG O(|E|)
Floyd-Warshall all pairs of vertices' shortest path O(|E|)

下节预告,MST
Prim 算法
Kruskal 算法

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 201,924评论 5 474
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 84,781评论 2 378
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 148,813评论 0 335
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,264评论 1 272
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,273评论 5 363
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,383评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,800评论 3 393
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,482评论 0 256
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,673评论 1 295
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,497评论 2 318
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,545评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,240评论 4 318
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,802评论 3 304
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,866评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,101评论 1 258
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,673评论 2 348
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,245评论 2 341

推荐阅读更多精彩内容