Graph-Based Algorithms: CSE373: Design and Analysis of Algorithms
Graph-Based Algorithms: CSE373: Design and Analysis of Algorithms
Graph-Based Algorithms: CSE373: Design and Analysis of Algorithms
Compute: 5
6
4
4. do RELAX(u, v, w)
5. for each edge (u, v) E O(E)
6. do if d[v] > d[u] + w(u, v)
7. then return FALSE
8. return TRUE
If the graph has no negative cycles: all simple shortest paths contain
at most n - 1 edges
δ(i, j) = lij(n-1) and lij(n) = lij(n+1). . . = lij(n-1)
Extending the Shortest Path
lij(m) = min {lik(m-1) + wkj}
1kn
k
j j
i * = i
k
2. L(1) = W
3. for m = 2 to n - 1
5. return L(n - 1)
2 L(m-1) = L(1) W
3 4 0 3 8 -4 0 3 8 -4
8
1 3 0 1 7 0 1 7
2
-4
1
-5
4 0 4 0
7
5 4 2 -5 0 2 -5 0
6
6 0 6 0
0 3 8 2 -4
3 0 -4 1 7
L(m) = L(2)
4 0 5 11 … and so on until L(4)
2 -1 -5 0 -2
8 1 6 0
Improving Running Time
No need to compute all L(m) matrices
If no negative-weight cycles exist:
L(m) = L(n - 1) for all m n – 1
We can compute L(n-1) by computing the sequence:
L(1) = W L(2) = W2 = W W
L(4) = W4 = W2 W2 L(8) = W8 = W4 W4 …
2 x n 1
n 1 2 lg( n1)
L W
FASTER-ALL-PAIRS-SHORTEST-PATHS(W)
1. n = W.rows
2. L(1) = W
3. m = 1
4. while m < n – 1
5. let L(2m) be a new n × n matrix
6. L(2m) = EXTEND-SHORTEST-PATHS(L(m), L(m))
7. m = 2*m
8. return L(m)
Given: 1
8
3
2
Directed, weighted graph G = (V, E) -4
1
-5
7
Negative-weight edges may be present 5 4
6
No negative-weight cycles could be present in the graph
Compute:
The shortest paths between all pairs of vertices in a graph
The Structure of a Shortest Path
For any pair of vertices i, j V, consider all paths from i
to j whose intermediate vertices are all drawn from
a subset {1, 2, …, k}
Find p, a minimum-weight path from these paths
p1
pu j
i
pt
k
j
i
Computing the Shortest Path Weights
dij(k) = wij if k = 0
min {dij(k-1) , dik(k-1) + dkj(k-1) } if k 1
The final solution: D(n) = (dij(n)):
dij(n) = (i, j) i, j V
j j
+ (k, j)
i i
(i, k)
D(k-1) D(k)
The Floyd-Warshall algorithm
1. n = W.rows
2. D(0) = W
3. for k = 1 to n
4. let D(k) = dij(k) be a new n × n matrix
5. for i = 1 to n
6. for j = 1 to n
7. dij(k) = min(dij(k-1), dik(k-1) + dkj(k-1))
8. return D(n)
Initialization:
Updating:
Example dij(k) = min {dij(k-1) , dik(k-1) + dkj(k-1) }
D(0) = W D(1)
2 1 2 3 4 5 1 2 3 4 5
3 4 1 0 3 8 -4 1 0 3 8 -4
8
1 3 2 0 1 7 2 0 1 7
2
-4
1
-5
3 4 0 3 4 0
7
5 4 4 2 -5 0 4 2 5 -5 0 -2
6
D(2) 5 6 0 5 6 0
1 2 3 4 5 D(3) D(4)
1 0 3 8 4 -4 0 3 8 4 -4 0 3 -1 4 -4
2 0 1 7 0 1 7 3 0 -4 1 -1
3 4 0 5 11 4 0 5 11 7 4 0 5 3
4 2 5 -5 0 -2 2 -1 -5 0 -2 2 -1 -5 0 -2
5 6 0 6 0 8 5 1 6 0
Example dij(k) = min {dij(k-1) , dik(k-1) + dkj(k-1) }
D(5) P(5)
2 1 2 3 4 5 1 2 3 4 5
3 4 1 0 1 -3 2 -4 1 - 3 4 5 1
8
1
2
3 2 3 0 -4 1 -1 2 4 - 4 2 1
-4 7
1
-5
3 7 4 0 5 3 3 4 3 - 2 1
5 4 4 2 -1 -5 0 -2 4 4 3 4 - 1
6
5 8 5 1 6 0 5 4 3 4 5 -
Source: 5, Destination: 1
Shortest path: 8
Path: 5 …1 : 5…4…1: 5->4…1: 5->4->1
Source: 1, Destination: 3
Shortest path: -3
Path: 1 …3 : 1…4…3: 1…5…4…3: 1->5->4->3