Recursion As A Problem Solving Technique: © 2006 Pearson Addison-Wesley. All Rights Reserved 6-1
Recursion As A Problem Solving Technique: © 2006 Pearson Addison-Wesley. All Rights Reserved 6-1
RecursionasaProblem
SolvingTechnique
6-1
Backtracking
Backtracking
Astrategyforguessingatasolutionand
backingupwhenanimpasseisreached
Recursionandbacktrackingcanbe
combinedtosolveproblems
6-2
Strategy:guessatasolution
Thereare4,426,165,368waystoarrange8
queensonachessboardof64squares
6-3
6-4
6-5
Figure 6-1
a) Five queens that cannot attack each other, but that can attack all of
column 6; b) backtracking to column 5 to try another square for the queen;
c) backtracking to column 4 to try another square for the queen and then considering
column 5 again
2006 Pearson Addison-Wesley. All rights reserved
6-6
Recursivestep
Ifyousuccessfullyplaceaqueeninthecurrentcolumn
Considerthenextcolumn
Ifyoucannotplaceaqueeninthecurrentcolumn
Youneedtobacktrack
6-7
6-8
Defining Languages
Alanguage
Asetofstringsofsymbols
Examples:English,Java
IfaJavaprogramisonelongstringofcharacters,the
languageJavaProgramsisdefinedas
JavaPrograms={stringsw:wisasyntacticallycorrect
Javaprogram}
6-9
Defining Languages
Alanguagedoesnothavetobeaprogrammingor
acommunicationlanguage
Example
Thesetofalgebraicexpressions
AlgebraicExpressions={w:wisanalgebraic
expression}
6-10
Defining Languages
Grammar
Statestherulesforformingthestringsinalanguage
Benefitofrecursivegrammars
Easeofwritingarecognitionalgorithmforthe
language
Arecognitionalgorithmdetermineswhetheragiven
stringisinthelanguage
6-11
6-12
Figure 6-3
A syntax diagram for Java identifiers
2006 Pearson Addison-Wesley. All rights reserved
6-13
6-14
6-15
6-16
Palindromes
Grammar
<pal>=emptystring|<ch>|a<pal>a|b<pal>b|
|Z<pal>Z
<ch>=a|b||z|A|B||Z
6-17
Palindromes
Recognitionalgorithm
isPal(w)
if (w is the empty string or w is of length 1) {
return true
}
else if (ws first and last characters are the
same letter ) {
return isPal(w minus its first and last
characters)
}
else {
return false
}
6-18
Language
L={w:wisoftheformAnBnforsomen0}
Grammar
<legalword>=emptystring|A<legalword>B
6-19
6-20
Algebraic Expressions
Threelanguagesforalgebraicexpressions
Infixexpressions
Anoperatorappearsbetweenitsoperands
Example:a+b
Prefixexpressions
Anoperatorappearsbeforeitsoperands
Example:+ab
Postfixexpressions
Anoperatorappearsafteritsoperands
Example:ab+
2006 Pearson Addison-Wesley. All rights reserved
6-21
Algebraic Expressions
Toconvertafullyparenthesizedinfixexpression
toaprefixform
Moveeachoperatortothepositionmarkedbyits
correspondingopenparenthesis
Removetheparentheses
Example
Infixexpression:((a+b)*c
Prefixexpression:*+abc
6-22
Algebraic Expressions
Toconvertafullyparenthesizedinfixexpression
toapostfixform
Moveeachoperatortothepositionmarkedbyits
correspondingclosingparenthesis
Removetheparentheses
Example
Infixform:((a+b)*c)
Postfixform:ab+c*
6-23
Algebraic Expressions
Prefixandpostfixexpressions
Neverneed
Precedencerules
Associationrules
Parentheses
Have
Simplegrammarexpressions
Straightforwardrecognitionandevaluation
algorithms
6-24
Prefix Expressions
Grammar
<prefix>=<identifier>|<operator><prefix><prefix>
<operator>=+||*|/
<identifier>=a|b||z
Arecognitionalgorithm
isPre()
size = length of expression strExp
lastChar = endPre(0, size 1)
if (lastChar >= 0 and lastChar == size-1 {
return true
}
else {
return false
}
6-25
Prefix Expressions
Analgorithmthatevaluatesaprefixexpression
evaluatePrefix(strExp)
ch = first character of expression strExp
Delete first character from strExp
if (ch is an identifier) {
return value of the identifier
}
else if (ch is an operator named op) {
operand1 = evaluatePrefix(strExp)
operand2 = evaluatePrefix(strExp)
return operand1 op operand2
}
2006 Pearson Addison-Wesley. All rights reserved
6-26
Postfix Expressions
Grammar
<postfix>=<identifier>|<postfix><postfix><operator>
<operator>=+||*|/
<identifier>=a|b||z
Athighlevel,analgorithmthatconvertsaprefix
expressiontopostfixform
if (exp is a single letter) {
return exp
}
else {
return postfix(prefix1) + postfix(prefix2) +
operator
}
6-27
Postfix Expressions
Arecursivealgorithmthatconvertsaprefixexpressionto
postfixform
convert(pre)
ch = first character of pre
Delete first character of pre
if (ch is a lowercase letter) {
return ch as a string
}
else {
postfix1 = convert(pre)
postfix2 = convert(pre)
return postfix1 + postfix2 + ch
}
6-28
Fullyparenthesizedexpressionsdonotrequire
Precedencerules
Rulesforassociation
6-29
6-30
Provepropertiesaboutrecursivealgorithms
Provethatarecursivealgorithmperformsacertain
amountofwork
6-31
6-32
6-33
6-34
Let
moves(N)bethenumberofmovesmadestartingwith
Ndisks
WhenN=1
moves(1)=1
6-35
Recurrencerelationforthenumberofmovesthat
solveTowersrequiresforNdisks
moves(1)=1
moves(N)=2*moves(N1)+1
ifN>1
6-36
6-37
Summary
Backtrackingisasolutionstrategythatinvolves
bothrecursionandasequenceofguessesthat
ultimatelyleadtoasolution
Agrammarisadevicefordefiningalanguage
Alanguageisasetofstringsofsymbols
Arecognitionalgorithmforalanguagecanoftenbe
baseddirectlyonthegrammarofthelanguage
Grammarsarefrequentlyrecursive
6-38
Summary
Differentlanguagesofalgebraicexpressionshave
theirrelativeadvantagesanddisadvantages
Prefixexpressions
Postfixexpressions
Infixexpressions
Acloserelationshipexistsbetweenmathematical
inductionandrecursion
Inductioncanbeusedtoprovepropertiesabouta
recursivealgorithm
2006 Pearson Addison-Wesley. All rights reserved
6-39