2. Dynamic program
2
﹡ Dynamic programming approach is similar to divide and conquer in
breaking down the problem into smaller and yet smaller possible
sub-problems.
﹡ Dynamic programming is used where we have problems, which can
be divided into similar sub-problems, so that their results can be re-
used.
﹡ There are two approaches to dynamic programming:
﹡ Top-down approach
﹡ Bottom-up approach
3. ﹡ The main use of dynamic programming is to solve optimization
problems.
﹡ There are two ways of applying dynamic programming:
﹡ Top-Down
﹡ Bottom-Up
Example
﹡ The following computer problems can be solved using dynamic
programming approach −
﹡ Fibonacci number series
﹡ Knapsack problem
﹡ All pair shortest path by Floyd-Warshall
﹡ Shortest path by Dijkstra 3
4. Single source shortest path
﹡ The single source shortest path algorithm is also known Bellman-
Ford algorithm is used to find minimum distance from source
vertex to any other vertex.
﹡ In a shortest- paths problem, we are given a weighted, directed
graphs G = (V, E), with weight function w: E → R mapping edges
to real-valued weights. The weight of path p = (v0,v1,….. Vk) is
the total of the weights of its constituent edges:
﹡ We define the shortest – path weight from u to v by δ(u,v) = min
(w (p): u→v), if there is a path from u to v, and δ(u,v)= ∞,
4
5. Bellman-ford algorithm
﹡ The Bellman-Ford algorithm is a single-source shortest path
algorithm.
﹡ This means that, given a weighted graph, this algorithm will
output the shortest distance from a selected node to all other
nodes.
﹡ Given a source vertex s from a set of vertices V in a weighted
graph where its edge weights w(u, v) can be negative, find the
shortest path weights d(s, v) from source s for all
vertices v present in the graph. If the graph contains a negative-
weight cycle, report it.
﹡ For example, consider the following graph:
5
6. 6
• The distance of vertex 0 from the
source is 0. Its path is [0]
• The distance of vertex 1 from the
source is -1. Its path is [0 —> 1]
• The distance of vertex 2 from the
source is 2. Its path is [0 —> 1 —
> 2]
• The distance of vertex 3 from the
source is -2. Its path is [0 —> 1 —
> 4 —> 3]
• The distance of vertex 4 from the
source is 1. Its path is [0 —> 1 —
> 4]
7. 7
• Total number of vertices
in the graph is 5, so all
edges must be processed
4 times.
• Let all edges are
processed in the following
order: (B, E), (D, B), (B,
D), (A, B), (A, C), (D, C),
(B, C), (E, D).