Design Analysis Algorithm- Unit-4
Design Analysis Algorithm- Unit-4
ntroduction:
In back tracking technique, we will solve problems in an efficient way, when
othermethods like greedy method and dynamic programming. The solution is based finding on
compared
one
to
XI=I
Q
or more vectors that maximize,
minimize, or satisfy a criterion function P(x1, Kn). Form a solution
. . IF3
at any pomt seems not promising. ignore it. All possible soutions require a set of constraints divided
nto two categories
I. Explicit Constraint: Explicit constraints are rules that restrict each xi to take on values only
4
50
from a given set. Ex: xn= 0 or l.
. Implicit Constraint: Implicit Constraints are rules that determine which of the tuples in the
xat3 xap2
Example:
Fig: Problem State
Solution States: These are the problem states S for which the path form the root to S defines a
Here are C, D are answer states. (A, C) and (A, C, D) are solution states.
tuple in the solutioa space.
Here, square nodes () indicate solution. For the above solution space, there exists 3 solution states 6.Live Node: A node which has been generated but whose children have not yet been generated
is live node.
These solution states represented in the form of tuples i.e., (ghk,B,D),(A,C,F) and (A,C,G) are the
solution states. Example 1: (1)
This node I is called as live node since the children of node I have not been generated.
Example:
Example 2:
In this, node l is not a live node but node 2, node 3 are live nodes.
4. State Space Tree: Is the set of paths from root node to other nodes. State space tree is the tree
organization of the solution of the so lution space
Example: State space tree ofa 4-queen problem.
3
4
o rl: n f
thesolution vector
have bren ass igned. ri} and n ae global
Here, 4, 5, 3 are live nodes because the children of these nodes not
yet been generated.
E-Node: The live nodes whose children are currently do
.
11
15
16
Algorithm: Recursive backtracking
Here, node 2 is E-node.
8. Dead Node: It is generated node, that is either not to be expanded further or one for which all Applications of Backtracking
Backtracking is an algorithm design technique that can effectively solve the larger instances of
of its children has been generated.
combinational problems. It follows a systematic approach for
obtaining solution to a problem. The
applications of backtracking include,
1) N-Queens Problem: This is generalizat
ion problem. If we take n=8 then the
problem is called as 8
queens problem. If we take n=4then the problem is called 4 queens
problem. A classic combinational
(a) problem is to place n queens on a n"n chess board so that no two attack, i.,e no two queens are on the
Nodes 1. 2, 3,aredend sodes. Since node 1's children geoerated and node 2, 3 are not expanded. same row, column or diagonal
Assumed that node 2 generated one more node, So, I, 3, 4 are dead nodes. Algorithm of n-queens problem is given below:
1 Algorithm NQueens(k, n)
Using backtracking, this procedure prints all
possible placements of n querns on an n x n
chessboard so that they are nonattacking.
b) for i= 1 to rn do
Fig: Dead nodes
General Method:
The basic idea of backtracking is to build up a vector, one component at a time and to test if Place(k, i) then
whether thc vector being formed has any chance of success.
The major of
advantage this algorithm is that
we can realize the fact that the partial vector
generated does not lead to an optimal solution. In such a situation that vector can be ignored. 11
k]-i
if
Backtracking algorithm determincs the solution by systematically searching the solution space
(k -
3 // ith coluinn. Otherwise it returns false. 1[| is a qucen I and move to next column
// global array wihose first (k 1) values have been set.
Abs(r) rurns the abolute value of r.
I to k -1 do
if ((r) = i) // Two iu the coluun
sane
or
(Abslrji) =Abs(j k})
10 1or iu Lte saune diagonalI
11 then return false;
12 return true;
13
Algorithm: Can a new queen be placed?
(
4Queens problem:
Consider a 44 cheasboard. Let there are 4 qucens The objective a placc there 4 gucens on
Fig: Exanple of Backtrack woiution to the 4qunenm proble
3-1,
4°4 chewboard in much a way that o two queens shoukd be plsced in the sane row, ame cokure or Hence the sohution of to4-qucens's peroblem u ai-2. 24 xd-3, 1emfirst queen
frst cokumn
is
paced in 2d cohuma second qacen is placed in 4th coBumn and third queen is placod
diagonal postion and fourth queen is placod n thrd cohumn
The explicit constraunts are 4 qucens are to be placed en 4°4 chessboards in 44 w*y.
The implicit constraints are no two queers are in the sane r u coàuma or dugonal
Row
Let (xl. 2, 3, x4} be the solution vector where xl cokumn oa which the quren i is place
Frt queei s placed n first row and lirst cohimn.
Row 2
Row3
The second qucen shaould not he in finst row and secocd cohamn it shoks t plcad n cond
row and in vecond, third or hurth codumn It we place in aecond aolums, both will be n ams
diagonal, so place it in third cokumn.
Row 4
B B
4
F: Potioe of the rer that in generated during Racktracking
We are unabie to place qucen J in third row, &go bacik to queern 2 ad pace d umes here q e n preblkm
A clamic aombenaleoriai problem in to place 8 queens on a *8 chess board so that
w
else attack. i,e m two queens are to the same row, cmkuman or diagona
Now, we *il ohe t queem problem by using similar procedure adapted tor 4 quees
probkm The algorithm of s quecrs problerm can be obained by plactng n=8, in N
queens aigornhm
We obere that, or every ekemed on the same daagonal wtuch rus trom the upper ett to the e u r
righ, ech eiemern has the same "res-coamn" value. Abo every elemet on the same agonal
which o a from upper ngm to kower ef bae the same "row*cotum" vale
18. 8 X2=2
O
rows columns
And columns say A:
This can be diagrammatically represented as follows
5 OQO0OOO
x-24
K4=7
xa-2
OOO
B B B
right). If we subtractright
values these cells say 2-1-=1,4-3=1,5-4-1, get same
to lower left
values, addif the we we
traverse
of
from upper say (2,3) (1,404,1)..we get
values when common we
bits these cells i,e 2+3=5, 1+4-5, 4+1=5. Hence, we say that,
on traversing from upper left to
lower right, if (m,n\a.b) are the diagonal elements(of a cell) than m-n=a-b or on traversing from Bx= B
xs*s
upper right to lower let ifm,n)(a,b) are the diagonal elements(ofa cel) then mt=atb. (13)
The solution of 8 queens problem can be obtained similar to the solution of 4 queens. 12
problem.Xl=3, X2=6, X3=2, X4=7, X5=1, X6-4, X7-8, X8=5,
The solution can be shown as 2) Sum of Subsets Problem
Given a set of n objects with weights
Subset S of the given set S, such that
(wl,w2,.. w3) and positive integer
a M. We have to finda
SS
Sum ofthe elements of subset S' is equal to M.
For example,
sum is equal
if a given set S=(123,) and M=5, then there exists sets S'0,2) and S'=(1,4) whose
to
M.
It also be noted
can
that some instance of the problem does not have any solution.
For
M=7.
example, if given set S=(1,3,5) and M-=7, then subset occurs for which the sum is equal to
a no
The
sum ofsubsets problem can be solved by using the back tracking approach. In this implicit
tree is created, which is a binary tree. The root of the tree is selected in such a way that it represents
that no decision is yet taken on any input. We assume that, the elements of the given set are arranged
increasing order.
k=U
SumOfSub(s,k + 1,r - tk]);
2
X2l X2-0
19 10
Algorithm: Recursive backtracking algorithm for sum of subsets
X X3=0 X3 x-0 xo1
Example: 27
Let m=31 and w= {7, 11, 13, 24} draw a portions of state space tree.
Solution: Initially we will pass some subset (0, 1, 55). The sum of all the weights from w is 55, i.e.,
=0 xat1 x4=0
3) Graph Coloring
Let b e a graph and m be a given positive integer. The graph coloring problem is to find if
the nodes of G
can be colored in such a
way that no two adjacent nodes have the same color, yet only
m
colors are
used. This is termed the m-colorability decision problem. The m-colorability
optimization problem asks for the smallest integer for which the graph G
integer is referred to as the chromatic number of the graph.
m canbe colored. This
repeat
10
1 Next highest color.
r[ki= {c[k+1) mod (n + 1);All//colors have been used
return; //
2
if (z[k} =l 0)tothen
n ddo
13 for j=
14 // Check if this color is
Figure. An Ex. Of graph coloring 15 // distinct from adjacent colors.
if((G[k.j! # 0) and (:[k} = zj])}
Algorithm mColoring(k) I f (k.j) isand edgeand if adj.
This algorithm was forined usiug the recursive backtrackiug 18 //vertives have thesame color.
schema. The graph is represented by its boolean adjaceney 19 then break;
uatrix G1:76,1: 7]. such
All assiguinents of 1,2.... , m to the
20
vertices of the graph that adjacent verticesindex
are 21 if G =n+1) then return;// New colur founud
distinct integers are printed. k is the
ASsignexl
of the next vertex io color. until (false); // Otherwise iry to find auother color.
. m"
n.m°)
12
blog: anilkumarprathipati.wordpress.com
blog: anilkumarprathipati.wordpress.com7
UNIT-V
49Hamitonian Cycle be BACKTRACKING UNIT-V
Let G =
(V, E)
a connected
BACKTRACKING
graph with n vertices. A Hamitonian cyce is a round-trip Root
along n edges ofG
starting position In other wordspath
that vists every vertex once and ret
uns to its
Hamtoan cycle begns a some vertex Vi E if a
G and the vertices of G are
01.1 12 Va+L then the edges (Vi Vi+) are in E, 1 visited in the order
and VL which are
and theK-n,
Vi are distinct except for VI
equal
Gvenag ph GVE}we bave to find the Hamitonian circuit using
backtracking approach
we start out erch fon any
zditrary vertex, say L This vertex 'x' becomes the
root of our implicit
Tee The Dext
adjaceat vertexs seected oa the asis of alpbabetical i or numerical order.
sage an arbrry r t a ay ¥ mekes a cytle with any verter other than verter 'o' then If at any
dead end is eacbed In this case we backtrack one
we say that
step and again the search begins
t t r vetea i sbould be oted thaz, after
backtracking the element from the
by selecting (d)
be removed The sexth partial soution must Next vertex s' is selected.
IEwe choose vertex I ' then we do not get the Hamiltonian cycle.
using back1racking is successful if a Hamikonian cycle is obtained. Root
Euge Consider a gh G{VE, * e bave tw find the Hamikonian circuit using backtracking
d
Cae
Soktion italy we start out search wich vertea 'I' the vertex 1' becomes the root of our ()
Dead end
Root The vertex adjacent to 5 is 2, 3, 4 but they are already visited. Thus, we get the dead end. So,
we backtrack one step and remove the vertex '5' from our partial
(a) so lution.
Nerr ae choose verter 2' adjacent to "1, asi comes frst in umerical order (2, 3.4). The vertex adjacent to '4' are 5,3,1 from which vertex S' has already beenchecked and
with vertex 1' but by choosing vertex "l' we do not get the Hamitonian cycle. So, we again
we are
left
Root backtrack one step.
Hence we select the vertex '5' adjacent to 3.
Root
} s eieced whicà s adjacent to '2' and which comes first in mumerical order
Net rerna
Roo
()
end
Dead
The vertex adjacent to '5' are (2,3,4) so vertex 4 is selected.
(i)
Dead end
The vertex adjacent to "4' are (1, 3, 5) so vertex' l ' is sclectod. Hence we get the Hamiltonian
O'solutio
Fig Construction of Hamilton Cyele using Backtrcking
vertex 1' is visited only once, 1- 2- 3-5- 4- 1.
vertex other
cyele as all the than the start Algorithm Hamiltonian{k)
the rerursive formulation of
Root
/ This algorithm uses
// backtrack ing to find all the Hamiltoninn cycles
//of a graph. The graph is stored as au aljaceucy
natrix G[l: u,1 : . All eycles begin at uode 1.
6
repeat
/ / Generate valucs for rlkj
NextValue(k); // Assign a legal next value to z[k).
10 if (r[k] =0) then return;
if (kn) then write (r[1 : n});
12 clsc Hamiltonian(k + 1);
13 }until (falsc);
14
Dead end
(h) Algorithm: Finding all Hamiltonian cyeles
O Solution
below. The number above each
The final implicit tree for the Hamiltonian circuit is shown
node indicates the order in which thesc nodes are visitcd.
15 blog: anilkumarprothipati.wordpress.com
blog: anilkumarprathipati.worodpress.com
UNIT-V
BACKTRACKING
1
2
Algorit hm NextValue(k)
3
I/zl:k- 1} is a path of k -1 distinct vertices. If r[k| =0, theu
novertex has as yet been axsigned to
r[k). After execution,
/ zk is assigned to the next highest
umbered vertex which
does uot
alrcady appear in r{l: k- 1} aud is conuerted by
6 a n edge to r k 1. Otherwise ik|
-
= 0. If k = n, then
1/ in addition r{k is counected to r[!.
9 repeat
10
rk= (r[k 1) mod (n + i); // Next vertex.
12 if (r[k] =
0) then return
if (Gz[k - 1}.z[k]} #0) then
14 { / / Is there an edge?
15 for j = I to k - do if (r{=r[ki) then break;
16 /7 Check for distiuctuess.
17 if i = k) then // f true, then the vertex is distinct.
18 if ((k < ra) or ({k =n) and G[r7|,r[1] #0))
19 then rcturn;
20
21 until (false);
22 }
Algorithm: Generating a next vertex
UNIT-V1 BRANCH AND BOUND UNIT-V1 BRANCH AND BOUND
Introduction:
Branch
and Bound refers to all state space search methods in which all children of the E- Next, delete element from
an 3 and these livequeue
3, 7, 8 are children of
and
take it E-node.
generate
nodes are killedasby bounding
children of node
the
functions. So we wil not
Node are generated before any other live node becomes the E-Node.
include in the queue.
Branch and Bound is the generalization of both graph search strategies, BFS and D-search.
A BFS like state space search is called as FIFO (First in first out) search as the list of
ive nodes in a first in first out.
. A D-search like state space search is called as LIFO (last in first out) search as the list of
14 5 6
Again delete an element an from queue. Take it as E-node. generate the children of 4.
live nodes in a last in first out list. Node9 is generated and killed by boundary function.
Live node is a node that has been generated but whose children have not yet been generated.
Example:
stack
Generate children of node I and place these live nodes into stack.
234
Now we will delete an element from queue, Le. node 2, next generate children of node 2
and place in this queue.
L34s 6 SLacs
Again remove an clement from stack, i.,e node 5 is removed and nodes generated by 5 . Least-cost()
are 10, 11 which are killed by bounded function, so we will not place 10, 11 into stack. 2. Add_node().
Least-cost0 finds a live node with least c(). This node is deleted from the list of live nodes and
returned.
Add_node0 to delete and add a live node from or to the list of live nodes.
Add_node(x)adds the new live node x to the list of live nodes. The list of live nodes be
implemented as a min-heap.
stack
Delete an element from stack. i,e node 6. Generate child of node 6, i,e 12, which is the BOUNDING
answer node, so search process terminates. A branch and bound method searches a state space tree using any search mechanism in
which all the children of the E-node are generated before another node becomes the E-
LCLeast Cost) Branch and Bound Search
I n both FFO and LIFO Brunch and Bound the selection rnules for the next E-node in rigid node.
and blind. The selection rule for the next E-node does not give any A good bounding helps to prune (reduce) efficiently the tree, leading to & faster
preferences to a node that has of
a very good chance ofgetting the scarch to an answer node quickly. exploration space. Each time a new answer node is found, the value of
the solution
In this we wil use ranking function orcost function. We generate the children of E-node, among upper can be updated.
these live nodes; we select a node which has minimum cost. By using ranking function we will Branch and bound algorithms are used for optimization problem where we deal directly
calculate the cost of each node. only with minimization problems. A maximization problem is easily converted toa
minimization problem by changing the sign of the objective function.
Leo
R O O0 minimiz 2Piti
L-S
snbject to
r, `
Initially we will takc node I as E-node. Generate children of node 1, the children are 2, 3,
= 0 or 1, 1 < i n
4. By using ranking function we will
calculate thecost of 2, 3, 4 nodes is =2, =3, ë 4
respectively. Now we will select a node which has minimum cost i,e node 2. For node 2, the
children are 5, 6. Between 5 and 6 we will seclect the node 6 since its cost minimum. Generate
sclect 12 since its cost (=I) is minimum. More
children of node 6 i,e 12 and 13. We will node
over 12 is the answer node. So, we terminate scarch process.
Control Abstraction for LC-search
in Ifx in
Let t be a state space tree and c() a cost for
function the nodes t. is node t, then
a
c(x) is the minimum cost of any answer node in the sub trec with root x. Thus, c(t) is the cost ofa
minimum-cost answer node in t.
LC search uses &to find an answer node. The algorithm uses two functions
Algoritha Reduce(p. w, n, m, I1, 72) For node 2, x=1, means we should place first item in the knapsack.
Variables are described in the discussion. U=10+10+12=32, make it as -32
// as
L=10+10*12+ (3/9*|8) = 32+638, we make t as -38
/ Pil/wlij 2 pli + 1i/wji t l}, 1<i<n. For node 3, x1=0, means we should not place first item in the knapsack.
U10+12=22, make it as -22
I1:= 12 :=0; L=10+12+ (5/9*18) = 10+12+10=32, we make it as -32
:Lbb(9, 0); 32
klargest j such that wj1|+ +ui <n;
for i = 1 to k do
-3
if (Ubb 0. (i})< g) >thenthen
I1=Iufi}: 2
else if (Lbb(0, {#}) y) q= Lbb{0,{i}; 2
for i= k +1 to n do Upper mumber = L
Lower number = U
if (Ubb({i}. P) < g) then /2 12u {i}; Next we will calculate difference ofupper bound and lower bound for nodes 2,3
else if (Lbb{{i},0) > q) then q :=Lbb({i},); For node 2, U-L=-32+38=6
For node 3, U-L=-22+32=10
Choose node 2, since it has minimum difference value of 6,
wa)-(2,4, 6, 9).
Solution: knapsack problem can be solved by using branch and bound technique. In this problem
we will calculate lower bound and upper bound for each node by weight ratio. Ater that,
tem profits and weights with respect profit
the of
Arange
place the first item in the knapsack. Remaining weight of knapsack is l5-2=13. Place nexttem
W2 m knapsack and the remaining weight of knapsack is 13-49, Place next item wJ, in knapsack
then the remaining weight of knapsack is 9-6-3. No fraction are allowed in calculation of upper -36
bound so Wa, cannot be placed in knapsack. 22
Proiit pitp2t p3,=10+10+12
So, Upper bound=32
since fractions allowed in Upper umber = L
To caculate Lower bound we can place W4 in knapsack are
6
blog: anilkumarpra thipati wordpress.com
blog: anilkumarprathipati wordpress.com
BRANCH AND BOUND
UNIT-VI
UNIT-VI1 BRANCH AND BOUND
are the next two nodes to B-nodes. Neither is expanded as for each, L >
-38 become Node 8 is
the next E-node. Nodes 10 and Il are generated; Node 10 is infeasible and so upper.killed. Node 11
-32 has L
(11)>upper and so is also
When node 12 is generated,
killed. Node 9 is expanded next.
12
Upper and ans are updated to -38 and 12 respectively. Node
joins the
queue of live nodes. Node 13 is killed before it can get onto the
-38. L (13)> upper. The
queue of live nodes
-32 22 as
only remaining live node is node 12. It has no
children and the search
terminates. The value ot upper and the path rom node 12 to the root is
4 output. So solution is
X=1, X2=1, X3=0, X4=1.
38 38
-32 38
-38, 20
-SR K20
Upper number =
Lower umber = U
b) Set AG,1) to a.
reduction and column reduction except for rows and columns containing
c) Apply row
to reduce the matrix.
only a. Let r is the total amount subtracted
d) Find (S)= ¢(R)+A(L)+r.
-38
2 until all nodes are visited.
Repeat step
-32
Example: Find the LC branch and bound solution for
cost matrix IS as tollows.
the travelling sales person problem whose
o 6
20 30 10 11
16 4 2
3
22 S 2 4
A Thecost matrix is3
19 6 18
16 4 7 16
method:
-20 Apply now reduction
from all values in the 1 row.
Deduct 10 (which is the minimum)
-38 -20 Deduct 2 (which is the minimum) from all values n the 2 row,
column. Similarly apply subtracted from columns 2), (1,3), (1, 4, (1,5).
of elements, which were
e) Find thethesum
cumulative sum of row wise
reduction and column wise reduction. The tree organization up to this as follows;
t) Obtain sum.
sum=Row wise reduction s u m + C o l u m n wise reduction Variable I indicate the next node to visit.
Cumulative reduced anda as upper
the starting state as lower bound
reduced sum to
Associate the cumulative
com
biog' anilkumarprathipati wordpress.
UNIT-VI BRANCH AND BOUND BRANCH AND BOUND
UNIT-VI
Step 2
Now comsider the path (1, 2)
Change all entries ofrow 1 and colurmn 4 ofA to o and also set A(4,1) to o.
Change all entries ofrow I and column 2 ofA to n and also set A (2, 1) to oo.
12 0
03 2
11 2 0 3 12 0
0 0
0 2 I1 0 0
15 12 0 Apply row and column reduction for the rows and columns whose rows and column are not
11 0 12
Apply row and column reduction for the rows and columns whose rows and column are not completely
completely . Then the resultant matrix is 12 11 o 0
Change all entries of row I and column 5 ofA to o and also set A(5,1) to o
There fore, as (S)= ¢(R)+A(1,2)+r > CS= 25 + 10 -0 35.
Now consider the path (1, 3)
Change all entries of row I and column 3 of A to o and also set A (3, 1) to o. 12 11 2
0 3 0
12 20 15 3 12
2 0 0 12
15 3 0 Apply row and column reduction for the
completelyyo
rows and columns whose rows and column are not
1I 0 12
Apply row and column reduction for the rows and columns whose rows and column are not 10 a 9 0
(4, 2) is minimum. Hence the matrix obtained for path (4, 2) is considered as reduced cost
matrix.
of the between
=
The cost
(S}28+ 11 +13 =52. minimum. Hence the matrix obtained for path (2, 5) is considered as reduced cost matrix.
A
Now Consider the path (2,2 and column 5 of A to and also set A(5,1) to .
0
Change all entriesof row The new possible path is (5, 3).
2811)
Numbers outside the node are values
, E3
-
3
blog: anilkurarprathipati.wordpress.com
17