path in distance

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.

Implementation deletemin insert/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|)



posted on 2012-02-28 11:03  grep  阅读(227)  评论(0编辑  收藏  举报