Professional Documents
Culture Documents
RAIK 283: Data Structures & Algorithms
RAIK 283: Data Structures & Algorithms
Dynamic Programming
Warshall’s and Floyd’sAlgorithm
Dr. Ying Lu
ylu@cse.unl.edu
3
Warshall’s algorithm: transitive closure
• Computes the transitive closure of a relation
• (Alternatively: all paths in a directed graph)
3 3
1 1
4 4 0 0 1 0
2 0 0 1 0 2
1 0 0 1 1 1 1 1
0 0 0 0 0 0 0 0
0 1 0 0 1 1 1 1
•…
•...
i P1 j
p2
k Vk
Vk-1
i p j
p
k Vk
p1
Vk-1 p2
i j
{
R(k)[i,j] =
R(k-1)[i,j]
or
(path using just 1, …, k-1)
j
Design and Analysis of Algorithms - Chapter 8 11
Warshall’s algorithm
3
3 1
1
2 4
2 4 3 R2
R1 1 0 0 1 0
R0
0 0 1 0 0 0 1 0 1 0 1 1
1 0 0 1 1 0 1 1 0 0 0 0
2 4 1 1 1 1
0 0 0 0 0 0 0 0
0 1 0 0 0 1 0 0
3 R4
3 R3 1
1 0 0 1 0 0 0 1 0
1 0 1 1 1 1 1 1
0 0 0 0 4 0 0 0 0
2 1 1 1 1
2 4 1 1 1 1
R0 = A R1 R2
0 0 1 0 0 0 1 0 0 0 1 0
1 0 0 1 1 0 1 1 1 0 1 1
0 0 0 0 0 0 0 0 0 0 0 0
0 1 0 0 0 1 0 0 1 1 1 1
R3 R4
0 0 1 0 0 0 1 0
1 0 1 1 1 1 1 1
0 0 0 0 0 0 0 0
1 1 1 1 1 1 1 1
0 1 0 0
0 0 1 0
0 0 0 1
0 0 0 0
•In D(k), dij(k): weight of the shortest path from ui to uj with all
intermediate vertices in an initial subset {u1, u2, … uk}
4 3
1
1
• Example: 6
1 5
2 4
3
Design and Analysis of Algorithms - Chapter 8 18
Floyd’s algorithm: all pairs shortest paths
Vk
ui p uj
ui p uj
• dij(0)=wij
FLOYD(G)
for i,j in [1..n]
d[i,j]=w(ui,uj)
for k in [1..n]
for i in [1..n]
for j in [1..n]
d[i,j]=min(d[i,j],d[i,k]+d[k,j])
D(0) = 0 3
2 0
7 0 1
6 0
FloydEnhanced(w[1..n, 1..n])
ShortestPath(i, j, p[1..n, 1..n])
for i,j in [1..n]
k = p[i, j]
d[i,j]=w(ui,uj)
if k 0
for i in [1..n] ShortestPath(i, k)
for j in [1..n] print(k)
p[i,j]=0 ShortestPath(k, j)
for k in [1..n]
for i in [1..n]
for j in [1..n]
if d[i,j] >d[i,k]+d[k,j]
d[i,j]=d[i,k]+d[k,j]
p[i,j] = k
p
k Vk
p1
Vk-1 p2
i p j
l
solution for a smaller subproblem is used for getting solutions for
multiple bigger subproblems
In-class exercise
What does dynamic programming have in common with
divide-and-conquer? What is a principal difference
between them?