Ch-8-Daa-Mb Students
Ch-8-Daa-Mb Students
f(n-1) + f(n-2)
3
Examples of Dynamic Programming Algorithms
4
Warshall’s Algorithm: Transitive Closure
• Computes the transitive closure of a relation
3 3
1 1 Presence of intermediate vertices
vertices = 1
0 0 1 0 0 0 1 0
1 0 0 1 1 1 1 1
4 0 0 0 0 4 0 0 0 0
2 2 1 1 1 1
0 1 0 0
5
Adjacency Matrix and Transitive-Closure
Adjacency Matrix, A={aij} of a directed graph is a Boolean
matrix that has 1 in its ith row and jth column if and only if
there is a directed edge from the ith vertex to the jth vertex.
7
Warshall’s Algorithm
Constructs transitive closure T as the last matrix in the sequence of n-
by-n matrices R(0), … , R(k), … , R(n) where
R(k)[i,j] = 1 iff there is nontrivial path from i to j with only first k
vertices(not higher than k) allowed as intermediate
K=0: No intermediate vertex
K=1: with 1 intermediate vertex
K=2: with 2 intermediate vertex……….
Note that R(0) = A (adjacency matrix),
R(n) = T (transitive closure)
The centeral point of the algorithm is that we can compute all the
elements of each matrix R(k) from its immediate predecessor R(k-1) in
8
series
Warshall’s Algorithm
It implies the following rules for generating R(k) from
R(k-1):
Rule 1: If an element in row i and column j is 1 in R(k-1),
it remains 1 in R(k)
Rule 2: If an element in row i and column j is 0 in R(k-1),
it has to be changed to 1 in R(k) if and only if the
element in its row i and column k and the element in its
column j and row k are both 1’s in R(k-1)
{
R(k)[i,j] =
R(k-1)[i,j]
or
(path using just 1 ,…,k-1)
j
10
Warshall’s Algorithm : Transitive
Closure
11
Warshall’s Algorithm
• Example: 1
1
6
1 5
4
2 3
13
Diagraph and its Weight Matrix
14
Floyd’s Algorithm
On the k-th iteration, the algorithm determines shortest paths
between every pair of vertices i, j that use only vertices among
1,…,k as intermediate
j
15
Floyd’s Algorithm
18
Prims Algorithm
Given n points , connect them in the cheapest
possible way so that there will be a path between
every pair of points. We can represent points by
vertices of a graph , possible connections with edges
of a graph and connection cost by the edge weight.
20
Example
21
22
Kruskals Algorithm
Sort the edges in nondecreasing order of
lengths
25
Example of Kruskal’s Algorithm(cont’d)
26
Efficiency
Algorithm looks easier than Prim’s but is
harder to implement (checking for cycles!)
This algorithm repeatedly chooses the
smallest-weight edge that does not form a
cycle.
Kruskal’s Algorithm is O(E log V ) using
efficient cycle detection.
27