Dynamic Programming
Dynamic Programming
DynamicProgramming
1. All pair shortest path problem
2. Travelling sales person problem
3. Single Source shortest path problem
• Dynamic programming was invented by Richard Bellman
in 1950.
• Dynamic programming technique follows bottom up
approach, the solution of the smallest sub problem is
stored in a table and it is used whenever required.
Characteristics of dynamic programming
• Optimal Substructure
If an optimal solution contains optimal subsolutions, then the problem
exhibits optimal substructure.
• Overlapping subproblem
When the recursive algorithm revisits same subproblem over and
over, the problem is said to have overlapping subproblem.
Characteristics of dynamic programming
• Optimal Substructure
B
A
E
C F
• Overlapping subproblem
• Overlapping subproblem
Similarities
1. Both technique view the original problem as a collection
of subproblems.
2. Both are recursive in nature.
Dissimilarities
g(3,{2,4}) = min(c32+g(2,{4}),
c34+g(4,{2}))
= min(13+18,12+13)=
25
g(4,{2,3}) =min(c42+g(2,{3}),
Finally from equation (1) we get,
g(1,{2,3,4}) = min { c12+ g(2,{3,4}),
c13+ g(3,{2,4}),
c14+ g(4,{2,3}) }
= min(10+25, 15+25, 20+23}
= min( 35, 40, 43)
= 35
Length of optimum tour is 35
A tour of this length can be constructed
as
Minimum of g(1,{2,3,4}) is obtained from c12+
g(2,{3,4})
so path is 12
Minimum of g(2,{3,4}) is obtained from
c24+g(4,{3})
so tour is 12 4 3 1
(j that minimize the RHS)
Bellman-Ford Algorithm
• Bellman –Ford algorithm computes shortest
path from a single source vertex to all other
vertices in a weighted directed connected
graph.
• This algorithm can be applied to graphs
containing negative edge weights.
• This algorithm works only if the graph has no
negative weight cycle.
• Bellman-Ford allows us to determine the
presence of negative weight cycle.
• Total complexity of the algorithm is O(V*E), V -
is the number of vertices and E number of
edges
Bellman-Ford Algorithm
Algorithm Bellman_Ford(G, W, S)
{ Initialize_Singe_Source(G,S)
Initialize_Singe_Source(G,S) {
for i= 1 to (|V|-1 ) for each vertex V in G
for each edge (U, V) in E(G) d[V] = infinite
Relax(U,V,W) p[V] = NIL
d[S] = 0
for each edge (U,V) in G }
if (d[V]> d[U] + W(U, V) )
Return False //Error: Negative Cycle
Exists
Return True // return d[], p[]
} Relax(U,V,W)
{
if (d[V]> d[U] + W(U, V) )
dist[V] =d[U] + W(U, V)
p[V]=U
}
Time Analysis - Bellman-Ford Algorithm
4 5 1 1-4 0+5=5
4 1-4 5
If(d[v]> d[u]+w(u,v))
return False (ie., negative weight cycle)