Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


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

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

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

3 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]

4 shortest() Void shortestpath(int v, int cost[][MAX_VERTICES], int dist [], int n, int found[]) { int i,u,w; for (i=0;i<n;i++) { found[i]=FALSE; dist [i] = cost[v][i]; } found[v]=TRUE; dist [v]=0; for(i=0;i<n-2;i++){ u=choose(dist,n,found); found[u]=TRUE; for(w=0;w<n;w++) if(dist [u]+cost[u][w] < dist [w]) dist [w] = dist [u]+cost[u][w]; } O(n^2)

5 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

6 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

7 BellmanFord() Void BellmanFord(int n, int v) { int i,k; for (i =0;i<n;i++) dist[i] = length[v][i]; for(k=2;k<=n-1;k++) for(each u s.t. u!=v and u has at least one incoming edge) for(each in the graph) if(dist([u]>dist[i]+length[i][u]) dist[u]=dist[i]+length[i][u]; } O(n^3)

8 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

9 AllLengths() Void AllLength(int n) { int i,j,k; for(i=0;i<n;i++) for(j=0;j<n;j++) a[i][j] = length[i][j]; for(k=0;k<n;k++) for(i=0;i<n;i++) for(j=0;j<n;j++) if((a[i][k]+a[k][j])<a[i][j]) a[i][j] = a[i][k]+a[k][j]; } O(n^3) 01 2 6 4 2 11 3

10 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


Download ppt "Shortest paths and transitive closure Data structure 2002/12/4."

Similar presentations


Ads by Google