Length of a Path The weight (length) of a path is the sum of the weights of its edges. adcbe Path p: Edge weights: w(a, b) = 7, w(b, c) = 2, w(c, d) = 1, w(d, e) = 5 Path weight w(p) = 15
Single-Source Shortest Paths A shortest path from vertex u to vertex v has the minimum weight among all paths connecting u to v. Problem Given a graph G = (V, E), where every edge e has a nonnegative weight w(e), and a source vertex s in V, find the shortest path from s to every other vertex.
An Example a s be f d c path s s-a s-a-b s-a-b-c s-a-d s-a-b-e s-a-b-e-f weight s a b c d e f 5
Applications Routing Telecommunications Robot path planning Building block for network algorithms...
Dijkstra’s Algorithm Idea: Successively compute u, u, …, u, where u = the kth closest vertex to s 1 2 n k u = s u is the closest vertex to s;i.e., w(s, u ) = min{ w(s,v) | (s, v) in E } u is the closest vertex to u or the second closest to s
How to Find u ? k+1 Let V = {u, u,…, u } 1 2 k Lemma The shortest path to u goes only through vertices in V. k k+1 Proof Suppose there exists a vertex x not in V but on the path to u. Then x is closer to s than u, a contradiction. k k +1 k+1k+1 s x u k+1k+1 V k
Implementation Maintain arrays d and pred. At beginning of kth iteration: d(v) = length of the shortest path from s to v that only contains vertices in V. k pred(v) = the predecessor of v in the above path. u is the vertex with minimum d-value in V(G) - V. k+1k+1 k
Relaxation After finding u, update d(v) for every neighbor v of u. k+1 s v w u s w v u d(v) = min{ d(v), d(u ) + w(u, v) } k+1 If d(v) decreases, set pred(v) = u. k+1
Dijkstra(G, w, s) for each vertex v in V(G) // initialization do d(v) = infinity pred(v) = NIL d(s) = 0 S = {} Q = V(G) // initializing priority queue while Q {} do u = Extract-Min(Q) // minimum d value in V-S S = S + {u} for each vertex v in Adj(u) do // adjacency lists if d(v) > d(u) + w(u, v) // relaxation then d(v) = d(u) + w(u, v) pred(v) = u
An Example a f e c b d s inf 2
a f e c b d s
a f e c b d s
a f e c b d s
a f e c b d s
a f e c b d s
a f e c b d s
a f e c b d s
a f e c b d s Shortest Path Tree The unique simple path from s to v in the tree is a shortest path from s to v.
Analysis Q build-queue extract-min decrease-key total Array O(n) O(n) O(1) O(n ) Heap O(n) O(lg n) O(lg n) O(m lg n) 2 n times m times