M4 - Chapter 8 1
M4 - Chapter 8 1
Dynamic Programming
• Dynamic Programming is mainly an optimization
over plain recursion. Wherever we see a recursive
solution that has repeated calls for same inputs,
we can optimize it using Dynamic Programming.
The idea is to simply store the results of
subproblems, so that we do not have to re-
compute them when needed later. This simple
optimization reduces time complexities from
exponential to polynomial.
• For example, if we write simple recursive solution
for Fibonacci Numbers, we get exponential time
complexity and if we optimize it by storing
solutions of subproblems, time complexity
reduces to linear.
1
https://www.youtube.com/watch?v=HC4kUZoIiv0
2
3
• The time efficiency and space efficiency of this algorithm are both in (nW ).
• The time needed to find the composition of an optimal solution is in O(n). 4
5
https://www.youtube.com/watch?v=T8w-7Brnvr4
Memory functions
6
7
• This algorithm may be less space-efficient than a bottom-up algorithm. But its time efficiency class is the same as
that of the bottom-up algorithm.
8
https://www.youtube.com/watch?v=Ar71s3mrl3c&t=616s
1. Warshall’s algorithm
DEFINITION The transitive closure (reach-ability matrix) of a directed graph with n vertices can be defined as
the n × n boolean matrix T = {tij}, in which the element in the ith row and the jth column is 1 if there exists a
nontrivial path (i.e., directed path of a positive length) from the ith vertex to the jth vertex; otherwise, tij is 0.
• We can generate the transitive closure of a digraph with the help of DFS or BFS. Performing either traversal
starting at the ith vertex gives the information about the vertices reachable from it and hence the columns that
contain 1’s in the ith row of the transitive closure. Thus, doing such a traversal for every vertex as a starting
point yields the transitive closure in its entirety.
• Since this method traverses the same digraph several times, we should hope that a better algorithm can be
found. It is called Warshall’s algorithm after Stephen Warshall, who discovered it. It is convenient to
assume that the digraph’s vertices and hence the rows and columns of the adjacency matrix are numbered
from 1 to n. Warshall’s algorithm constructs the transitive closure through a series of n × n boolean matrices:
9
EXAMPLE:
10
time efficiency is Θ(n3)
11
https://www.youtube.com/watch?v=oNI0rf2P9gE
12
EXAMPLE:
13
time efficiency is Θ(n3)
14
Tutorial:
1. Apply Warshall’s algorithm to find the transitive closure of the digraph defined by
the following adjacency matrix and graph:
a.
b.
2. Apply Floyd’s Algorithm to the given graph for finding the All-Pairs Shortest-Paths
a. b. c.
By:
Dr. Geeta S Hukkeri
15