Design and Analysis of Algorithm: Graphs
Design and Analysis of Algorithm: Graphs
Lecture 32
Graphs
Sahar Ajmal
Lecturer
Department of Computer Science
1
Today’s Lecture
Shortest Path
All-Pairs Shortest Paths Problem
2
Shortest path
In general, in graph theory the shortest path between
two vertices in a graph is a path between those two
vertices in such way that the sum of weights of edges
in that path is the smallest than the sum of weights of
edges in any path between those two vertices provided
the graph is a weighted graph.
3
All-Pairs Shortest Paths Problem
4
Floyd-Warshall algorithm
5
Main idea
6
Matrix Representation
7
Floyd Warshall Algorithm
1. Floyd_Warshall (W) {
2. for i = 1 to n do { / / initialize
3. for j = 1 to n do{
4. d[i,j] = W[i,j]
5. pred[i,j] = null
6. }
7. }
8. for k = 1 to ndo / / use intermediates {1..k}
9. for i = 1 to n do / / ...from i
10. for j = 1 to n do / / ...to j
11. if (d[i,k] + d[k,j]) < d[i,j]) {
12. d[i,j] = d[i,k] + d[k,j] / / new shorter path length
13. pred[i,j] = k } / / new path is through k
14. return d / / matrix of final distances
15. }
8
Compute shortest path using
predecessor information
The pred[i, j] can be used to extract the final path.
Here is the idea, whenever we discover that the shortest path from
i to j passes through an intermediate vertex k, we set pred[i,j] = k.
If the shortest path does not pass through any intermediate vertex,
then pred[i, j] = null.
To find the shortest path from i to j, we consult pred[i,j]. If it is
null, then the shortest path is just the edge (i, j). Otherwise, we
recursively compute the shortest path from i to pred[i, j] and the
shortest path from pred[i, j] to j.
9
Example
10
Initially
P(0) =
11
if (d[i,k] + d[k,j]) < d[i,j]) {
P(0) =
P(1) =
12
if (d[i,k] + d[k,j]) < d[i,j]) {
2nd Iteration: k=2 d[i,j] = d[i,k] + d[k,j]
pred[i,j] = k }
P(1) =
P(2) =
13
if (d[i,k] + d[k,j]) < d[i,j]) {
P(2) =
P(3) =
14
if (d[i,k] + d[k,j]) < d[i,j]) {
d[i,j] = d[i,k] + d[k,j]
4th Iteration: k=4 pred[i,j] = k }
P(3) =
P(4) =
15
Shortest Path from 1 to 4
1->4 i-e 1->4
Shortest Path from 4 to 3
4->3 i-e 4->2->3
Shortest Path from 3 to 2
3->1->4->2
16
Analysis of Floyd Warshall Algorithm
O(n3)
17
Task
18
Initially
19
Questions?
Question in my Should I ask
mind is ? this ?
hmmmmmmmmm?
Sorry I was
sleeping sir !