Professional Documents
Culture Documents
DSFDSF
DSFDSF
Backtracking
Dr.P.Baskaran,
Asst. Professor Senior Grade,
SCOPE, VIT, Vellore
baskaran.p@vit.ac.in
9095074951
❖ It searches for a solution to a problem among all the available options. Initially, we start the
backtracking from one possible option and if the problem is solved with that selected option then we
return the solution else we backtrack and select another option from the remaining available
options.
❖ When none of the options gives the solution, we understand that backtracking won’t give any
solution to that particular problem.
❖ Here the process of finding the solution from the various option available is repeated recursively
until we don’t find the solution or we reach the final state.
When to use a Backtracking algorithm?
When we have multiple choices, then we make the decisions from the available
choices. In the following cases, we need to use the backtracking algorithm:
❖A piece of sufficient information is not available to make the best choice, so we use
the backtracking strategy to try out all the possible solutions.
❖Each decision leads to a new set of choices. Then again, we backtrack to make new
decisions.
Backtracking: Idea
• Backtracking is a technique used to solve problems with a large search space, by
systematically trying and eliminating possibilities.
Portion A
Junction
Portion B
Backtracking:
One strategy would be to try going through
Portion A of the maze.
If you get stuck before you find your way out,
then you "backtrack" to the junction. Portion B
Portion A
NOT lead you out of the maze,
so you then start searching in Portion B
Backtracking
• Clearly, at a single junction you could have even more than 2 choices.
• The backtracking strategy says to try each choice, one after the other,
• If you try all choices and never found a way out, then
there IS no solution to the maze.
C
B
A
Backtracking: Idea
start
?
?
?
dead end
?
dead end
dead end
success!
dead end dead end
Applications of Backtracking
• N-queens problem
• Graph coloring
• Hamiliton cycle
Subset Sum problem
• Subset sum problem is the problem of finding a subset such that the
sum of elements equal a given number.
Example:
• Given the following set of positive numbers:
{ 5,10,12,13,15,18}
• We need to find if there is a subset for a given sum say 30:
{ 5,10,15}
{5,12,13}
{12,18}
Bark tertleng
hosa soluhaM a t
Rarnenng
Saho Sahi ha Cont
z,
nol Conyidera
Conidevp
1 (Tnenced
h 6
7-Revels a
h Sohdis tre
a ey hexlr e6.
0c2 Tme onplor
O73
,
5.68
Ry20
27, 46
Xy 0
40,33 a7, 33
Stop
batktratk
27,1 30
Bounan,
unui 7.0
L30
3o BT ST
42 Z 30.
5, 10, 1r Oned h e
Solutioo