80 likes | 268 Views
All Pairs Shortest Path. Find shortest paths of every pair of vertices Simple Solution Run Dijkstra or Bellman-Ford |V| time, for each starting vertex Has |V| copy of dist[] , each for each starting point. Divide and Conquer Version.
E N D
All Pairs Shortest Path • Find shortest paths of every pair of vertices • Simple Solution • Run Dijkstra or Bellman-Ford |V| time, for each starting vertex • Has |V| copy of dist[], each for each starting point
Divide and Conquer Version • Let Dm(a,b) be the shortest distance from a to b that has at most m edges • Does Dm-1(a,b) help us find Dm(a,b) ?
Finding Dm(a,b) • What could Dm(a,b) be? • It uses less than m edge • Hence Dm(a,b) = Dm-1(a,b) • It uses exactly m edge • Because sub-path must be a shortest path as weel • It’s Dm-1(a,k) + l[k,b] • So, we have our recursion • Dm(a,b) = min( Dm-1(a,b) , mink(Dm-1(a,k) + l[k,b] ) ) • = mink(Dm-1(a,k) + l[k,b] ) Because l[b,b] = 0
The Code Procedure UpdateD(Din, Dout) //Input: A matrix Din contain the minimum weight from every pair of vertices using less than m edge //Output: A matrix Dout contain the minimum weight from every pair of vertices using less than or equal to m edge for i ← 1 to n do for j ← 1 to n do Dout[i][j] = + for k ← 1 to n do Dout[i][j] = min (Dout[i][j], Din[i][j] + l[a][b]) Procedure AllPair(l, n) //Input: Graph G = (V,E), directed or undirected; vertex s V; positive edge lengths l //Output: A matrix D contain the minimum weight from every pair of vertices D = l For m ← 2 to n do TmpD = D UpdateD(TmpD,D);
Floyd-Warshall • Instead of iterate on “number of edges” • Use size “of allowed vertices” • Let Dm(a,b) be the shortest distance from a to b that can use only vertices 1 to m • Does Dm-1(a,b) help us find Dm(a,b) ? Cannot use vertex m
Finding Dm(a,b)of Floyd-Warshall • What could Dm(a,b) be? • It does not use vertex m • Hence, Dm(a,b) = Dm-1(a,b) • It uses vertex m • Hence, Dm(a,b)must be • A …… M ……. B Some shortest path from A to M Dm-1(a,m) Some shortest path from M to B Dm-1(m,b)
The Recursion Dm(a,b) =min( Dm-1(a,b), mink(Dm-1(a,k)+Dm-1 (k,b) ) )
The Code Procedure FloydWarshall(l, n) //Input: Graph G = (V,E), directed or undirected; vertex s V; positive edge lengths l //Output: A matrix D contain the minimum weight from every pair of vertices D = l For k ← 1 to n do For i ← 1 to n do For j ← 1 to n do d[i][j] = min ( d[i][j], d[i][k]+d[k][j] );