Graph – Shortest Path from
all vertices
P VASUKI
Dijkstra - Issue
• Doesn’t converge on negative
weight.
Floyd Warshall Algorithm –All Pair
Shortest Path Algorithm –Dynamic
Programming
Suppose we are given a directed graph
G=(V,E) and a weight function w: E->R.
We assume that G does not contain cycles
of weight 0 or less.
The All-Pairs Shortest Path Problem is to
find the length of the shortest path between
any pair of vertices in G.
Floyd Warshall Algorithm
Floyd-Warshall(W)
n = # of rows of W;
D(0) = W;
for k = 1 to n do
for i = 1 to n do
for j = 1 to n do
dij(k) = min{dij(k-1) , dik(k-1) + dkj(k-1)};
od;
od;
od;
return D(n);
Time and Space Complexity
The running time is obviously O(n3).
However, in this version, the space
requirements are high. One can reduce
the space from O(n3) to O(n2) by
using a single array d.
Example
• Find Shortest Path of given graph
Initialization: (k = 0)
• Iteration 1: (k = 1) Shorter paths
from 2 ↝ 3 and 2 ↝ 4 are found
through vertex 1
• Iteration 2: (k = 2) Shorter paths
from 4 ↝ 1, 5 ↝ 1, and 5 ↝ 3 are
found through vertex 2
• Iteration 3: (k = 3) No shorter
paths are found through vertex 3
• Iteration 4: (k = 4) Shorter paths from 1
↝ 2, 1 ↝ 3, 2 ↝ 3, 3 ↝ 1, 3 ↝ 2, 5 ↝ 1, 5
↝ 2, 5 ↝ 3, and 5 ↝ 4 are found through
vertex 4
• Iteration 5: (k = 5) No shorter paths
are found through vertex 5
• The final shortest paths for all pairs is
given by
More Example
• On Board ..
Additional Reference - Visualization
Thanks to University of San Francisco
• https://www.cs.usfca.edu/~galles/vi
sualization/Floyd.html