path in distance

本文深入探讨了Breadth-First Search (BFS)算法如何用于计算图中两个节点之间的最短距离,并通过引入Dijkstra's shortest-path算法,扩展了BFS在具有不同边长权重图的应用范围。文章详细阐述了算法的时间复杂性和实现细节,同时对比了不同优先级队列实现对算法性能的影响。

Distance

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

A conveninent way to compute distances from s to the other vertices is to proceed layer by layer.

Once we have picked out the nodes at distance k, the nodes at k+1 are easily determined:

they are precisely the as-yet-unseen nodes that are adjacent to the layer at distance k.

 

BFS(Breadth-First-Search) implements this simple reasoning.

Initially the Queue Q consists only of s, the one node at distance 0. And for each subsequent distance

d=1,2,3..., there is a point in time at which Q contains all the nodes at distance d and nothing else.

As these nodes are processed, their as-yet-unseen neighbors are injected into the end of the queue.

def bfs(G,s):
"""Input: Graph G=(V,E)"""
"""Output: For all vertices u reachable from s, dist(u) is set to the distance from s to u"""

for all u in 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) in E:
if dist(v) = ∞:
inject(Q,v)
dist(v)=dist(u)+1


Time: O(|V|+|E|)

Breadth-First-Search treats all edges as having the same length.

For the remainder, we will deal with this more general scenario, annotating every edge e in E with 

a length le, If e=(u,v), we will sometimes also write l(u,v) or luv.

BFS finds shortest paths in any graph whose edges have unit length, Can we adapt it to a more general graph G=(V,E), whose edge length l are positive integers?

Dijkstra's shortest-path algorithm
def dijkstra(G,l,s):
"""Input: Graph G=(V,E), positive edge length"""
"""Output: for all vertices u reachable from s, dist(u) is set to the distance from s to u""""

for all u in V:
dist(u)=∞
prev(u)=None

dist(s)=0

H=makequeue(V) (using dist-values as keys)

while H is not empty:
u=deletemin(H)
for all edges (u,v) in E:
if dist(v) > dist(u)+l(u,v):
dist(v)=dist(u)+l(u,v)//must be non-negative
prev(v)=u
decreaseKey(H,v)

Time:

the running time depends heavily on the priovity queue implementation used.

Implementationdeletemininsert/decreasekey|V|*deletemin+(|V|+|E|)*insert
Array O(|V|) O(1) O(|V|2)
Binary Heap  O(log|V|) O(log|V|) O(|V|+|E|)log(|V|)
d-ary Heap  O(dlog|V|/logd) O(log|V|/logd) O(|V|*d+|E|)log(|V|)/logd
 Fibonacci Heap O(log|V|) O(1)(amortized) O(|V|log|V|+|E|)



转载于:https://www.cnblogs.com/grep/archive/2012/02/28/2371162.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值