# Shortest paths and transitive closure Data structure 2002/12/4.

## Presentation on theme: "Shortest paths and transitive closure Data structure 2002/12/4."— Presentation transcript:

Shortest paths and transitive closure Data structure 2002/12/4

Is there a path? How short it can be?  Single source/ All destinations –Nonnegative edge costs –General weights  All-pairs shortest path  Transitive closure

Single source all destinations Dijkstra’s algorithm  A spanning tree again  For nonnegative edge costs (Why?)  Start from a vertex v, greedy method  dist[w]: the shortest length to w through S v u w length( ) dist[w] dist[u]

shortest() Void shortestpath(int v, int cost[][MAX_VERTICES], int dist [], int n, int found[]) { int i,u,w; for (i=0;i { "@context": "http://schema.org", "@type": "ImageObject", "contentUrl": "http://images.slideplayer.com/13/4035016/slides/slide_4.jpg", "name": "shortest() Void shortestpath(int v, int cost[][MAX_VERTICES], int dist [], int n, int found[]) { int i,u,w; for (i=0;i

An example 1 0 2 7 3 4 5 6 San Francisco Los Angeles Denver Chicago Boston New York Miami New Orleans 1500 250 1000 900 1400 1000 1700 1200 800 1000 300

Single source all destinations BellmanFord algorithm  For general weights  Path has at most n-1 edges, otherwise…  dist k [u]: from v to u, has at most k edges  0 1 2 3 4 5 6 6 5 5 1 -2 3 3

BellmanFord() Void BellmanFord(int n, int v) { int i,k; for (i =0;idist[i]+length[i][u]) dist[u]=dist[i]+length[i][u]; } O(n^3)

All-Pairs shortest paths  執行 n 次 single source all destinations algo.  Dynamic programming strategy – 利用 recursive formula 來表示 – 好好地 implement recursive formula, 用 table 輔助  A k [i][j] ≡ shortest length from i to j through no intermediate vertex greater than k  A -1 [i][j] = length[i][j]  A k [i][j] = min{A k-1 [i][j], A k-1 [i][k]+ A k-1 [k][j], k≥0

AllLengths() Void AllLength(int n) { int i,j,k; for(i=0;i { "@context": "http://schema.org", "@type": "ImageObject", "contentUrl": "http://images.slideplayer.com/13/4035016/slides/slide_9.jpg", "name": "AllLengths() Void AllLength(int n) { int i,j,k; for(i=0;i

Transitive closure  Definition: transitive closure matrix, A + –A + [i][j] = 1, if there’s a path of length > 0 from i to j –A + [i][j] = 0, otherwise  Definition: reflexive transitive closure matrix, A* –A*[i][j] = 1, if there’s a path of length >= 0 from i to j –A*[i][j] = 0, otherwise  O(n^3), by AllLengths()  O(n^2), an undirected graph, by connected check