4 Dynamic Programming-Lec
4 Dynamic Programming-Lec
4 Dynamic Programming-Lec
• Source S, Destination T
• By greedy method: shortest path is ???
• By DP: shortest path is: ???
The shortest path
• Given a multi-stage graph, how can we find a shortest
path?
–Forward approach: Let p(i,j) denote the minimum cost
path from vertex j to the terminal vertex T. Let COST(i,j)
denote the cost of p(i,j) path. Then using the forward
approach, we obtain:
COST(i,j) = min {COST(i,j), c(i,k) + COST(k,j)}
–Backward approach: Let p(i,j) be a minimum cost path
from vertex S to a vertex j in Vi . Let COST(i,j) be the
cost of p(i,j).
COST(i,j) = min {COST(i,j), COST(i,k) + c(k,j)}
NB. If (i, j) is not element of E then COST(i, j) = + inf.
Cont..
Example
•Consider the following example to understand the concept of
multistage graph.
Cont..
• According to the formula, we have to calculate the cost (i,
j) using the following steps.
Step-1: Cost (K-2, j)
• In this step, three nodes (node 4, 5. 6) are selected as j. Hence,
we have three options to choose the minimum cost at this step.
• Cost(3, 4) = min {c(4, 7) + Cost(7, 9),c(4, 8) + Cost(8, 9)} = 7
• Cost(3, 5) = min {c(5, 7) + Cost(7, 9),c(5, 8) + Cost(8, 9)} = 5
• Cost(3, 6) = min {c(6, 7) + Cost(7, 9),c(6, 8) + Cost(8, 9)} = 5
Step-2: Cost (K-3, j)
• Two nodes are selected as j because at stage k - 3 = 2 there are
two nodes, 2 and 3. So, the value i = 2 and j = 2 and 3.
• Cost(2, 2) = min {c(2, 4) + Cost(4, 8) + Cost(8, 9),c(2, 6) +
• Cost(6, 8) + Cost(8, 9)} = 8
• Cost(2, 3) = {c(3, 4) + Cost(4, 8) + Cost(8, 9), c(3, 5) +
Cost(5, 8)+ Cost(8, 9), c(3, 6) + Cost(6, 8) + Cost(8, 9)} = 10
Cont..
Step-3: Cost (K-4, j)
•Cost (1, 1) = {c(1, 2) + Cost(2, 6) + Cost(6, 8) + Cost(8, 9), c(1,
3) + Cost(3, 5) + Cost(5, 8) + Cost(8, 9))} = 12
•Hence, the path having the minimum cost is 1→ 3→ 5→ 8→ 9.
Algorithm
procedure shortest_path (COST[], A[], n)
//cost[i,j] is the cost of edges[i,j] and A[i,j] is the shortest path from
i to j
//cost[i,i] is 0.0
for i = 1 to n do
for j = 1 to n do
A(i, j) := COST(i, j) //copy cost into A
for k = 1 to n do
for i = 1 to n do
for j = 1 to n do
A(i, j ) = min(A(i, j), A(i,k) + A(k,j));
end for
end for
end for
return A(1..n,1..n)
end shortest_path
This algorithm runs in time O( n3 )