0% found this document useful (0 votes)
41 views39 pages

Recursion As A Problem Solving Technique: © 2006 Pearson Addison-Wesley. All Rights Reserved 6-1

The document discusses recursion and how it can be used to solve problems like the eight queens problem and Towers of Hanoi. It also covers defining languages with grammars and examples of languages like palindromes and expressions.

Uploaded by

talhaaftab728
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
41 views39 pages

Recursion As A Problem Solving Technique: © 2006 Pearson Addison-Wesley. All Rights Reserved 6-1

The document discusses recursion and how it can be used to solve problems like the eight queens problem and Towers of Hanoi. It also covers defining languages with grammars and examples of languages like palindromes and expressions.

Uploaded by

talhaaftab728
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 39

Chapter 6

RecursionasaProblem
SolvingTechnique

2006 Pearson Addison-Wesley. All rights reserved

6-1

Backtracking
Backtracking
Astrategyforguessingatasolutionand
backingupwhenanimpasseisreached

Recursionandbacktrackingcanbe
combinedtosolveproblems

2006 Pearson Addison-Wesley. All rights reserved

6-2

The Eight Queens Problem


Problem
Placeeightqueensonthechessboardsothatno
queencanattackanyotherqueen

Strategy:guessatasolution
Thereare4,426,165,368waystoarrange8
queensonachessboardof64squares

2006 Pearson Addison-Wesley. All rights reserved

6-3

The Eight Queens Problem


Anobservationthateliminatesmanyarrangements
fromconsideration
Noqueencanresideinaroworacolumnthatcontains
anotherqueen
Now:only40,320arrangementsofqueenstobe
checkedforattacksalongdiagonals

2006 Pearson Addison-Wesley. All rights reserved

6-4

The Eight Queens Problem


Providingorganizationfortheguessingstrategy
Placequeensonecolumnatatime
Ifyoureachanimpasse,backtracktotheprevious
column

2006 Pearson Addison-Wesley. All rights reserved

6-5

The Eight Queens Problem

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

The Eight Queens Problem


Arecursivealgorithmthatplacesaqueenina
column
Basecase
Iftherearenomorecolumnstoconsider
Youarefinished

Recursivestep
Ifyousuccessfullyplaceaqueeninthecurrentcolumn
Considerthenextcolumn

Ifyoucannotplaceaqueeninthecurrentcolumn
Youneedtobacktrack

2006 Pearson Addison-Wesley. All rights reserved

6-7

The Eight Queens Problem


Figure 6-2
A solution to the Eight Queens
problem

2006 Pearson Addison-Wesley. All rights reserved

6-8

Defining Languages
Alanguage
Asetofstringsofsymbols
Examples:English,Java
IfaJavaprogramisonelongstringofcharacters,the
languageJavaProgramsisdefinedas
JavaPrograms={stringsw:wisasyntacticallycorrect
Javaprogram}

2006 Pearson Addison-Wesley. All rights reserved

6-9

Defining Languages
Alanguagedoesnothavetobeaprogrammingor
acommunicationlanguage
Example
Thesetofalgebraicexpressions
AlgebraicExpressions={w:wisanalgebraic
expression}

2006 Pearson Addison-Wesley. All rights reserved

6-10

Defining Languages
Grammar
Statestherulesforformingthestringsinalanguage

Benefitofrecursivegrammars
Easeofwritingarecognitionalgorithmforthe
language
Arecognitionalgorithmdetermineswhetheragiven
stringisinthelanguage

2006 Pearson Addison-Wesley. All rights reserved

6-11

The Basics of Grammars


Symbolsusedingrammars
x|ymeansxory
xymeansxfollowedbyy
(Inxy,thesymbolmeansconcatenate,orappend)
<word>meansanyinstanceofwordthatthe
definitiondefines

2006 Pearson Addison-Wesley. All rights reserved

6-12

The Basics of Grammars


Javaidentifiers
AJavaidentifierbeginswithaletterandisfollowedby
zeroormorelettersanddigits

Figure 6-3
A syntax diagram for Java identifiers
2006 Pearson Addison-Wesley. All rights reserved

6-13

The Basics of Grammars


Javaidentifiers
Language
JavaIds={w:wisalegalJavaidentifier}
Grammar
<identifier>=<letter>|<identifier><letter>|<
identifier><digit>
<letter>=a|b||z|A|B||Z|_|$
<digit>=0|1||9

2006 Pearson Addison-Wesley. All rights reserved

6-14

The Basics of Grammars


Recognitionalgorithm
isId(w)
if (w is of length 1) {
if (w is a letter) {
return true
}
else {
return false
}
}
else if (the last character of w is a letter or a digit) {
return isId(w minus its last character)
}
else {
return false
}

2006 Pearson Addison-Wesley. All rights reserved

6-15

Two Simple Languages:


Palindromes
Astringthatreadsthesamefromlefttorightasit
doesfromrighttoleft
Examples:radar,deed
Language
Palindromes={w:wreadsthesamelefttorightas
righttoleft}

2006 Pearson Addison-Wesley. All rights reserved

6-16

Palindromes
Grammar
<pal>=emptystring|<ch>|a<pal>a|b<pal>b|
|Z<pal>Z
<ch>=a|b||z|A|B||Z

2006 Pearson Addison-Wesley. All rights reserved

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
}

2006 Pearson Addison-Wesley. All rights reserved

6-18

Strings of the form AnBn


AnBn
ThestringthatconsistsofnconsecutiveAsfollowed
bynconsecutiveBs

Language
L={w:wisoftheformAnBnforsomen0}

Grammar
<legalword>=emptystring|A<legalword>B

2006 Pearson Addison-Wesley. All rights reserved

6-19

Strings of the form AnBn


Recognitionalgorithm
isAnBn(w)
if (the length of w is zero) {
return true
}
else if (w begins with the character A and ends
with the character B) {
return isAnBn(w minus its first and last
characters)
}
else {
return false
}
2006 Pearson Addison-Wesley. All rights reserved

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

2006 Pearson Addison-Wesley. All rights reserved

6-22

Algebraic Expressions
Toconvertafullyparenthesizedinfixexpression
toapostfixform
Moveeachoperatortothepositionmarkedbyits
correspondingclosingparenthesis
Removetheparentheses
Example
Infixform:((a+b)*c)
Postfixform:ab+c*

2006 Pearson Addison-Wesley. All rights reserved

6-23

Algebraic Expressions
Prefixandpostfixexpressions
Neverneed
Precedencerules
Associationrules
Parentheses
Have
Simplegrammarexpressions
Straightforwardrecognitionandevaluation
algorithms

2006 Pearson Addison-Wesley. All rights reserved

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
}

2006 Pearson Addison-Wesley. All rights reserved

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
}

2006 Pearson Addison-Wesley. All rights reserved

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
}

2006 Pearson Addison-Wesley. All rights reserved

6-28

Fully Parenthesized Expressions


Toavoidambiguity,infixnotationnormally
requires
Precedencerules
Rulesforassociation
Parentheses

Fullyparenthesizedexpressionsdonotrequire
Precedencerules
Rulesforassociation

2006 Pearson Addison-Wesley. All rights reserved

6-29

Fully Parenthesized Expressions


Fullyparenthesizedexpressions
Asimplegrammar
<infix>=<identifier>|(<infix><operator><
infix>)
<operator>=+||*|/
<identifier>=a|b||z
Inconvenientforprogrammers

2006 Pearson Addison-Wesley. All rights reserved

6-30

The Relationship Between


Recursion and Mathematical
Induction
Astrongrelationshipexistsbetweenrecursionand
mathematicalinduction
Inductioncanbeusedto

Provepropertiesaboutrecursivealgorithms
Provethatarecursivealgorithmperformsacertain
amountofwork

2006 Pearson Addison-Wesley. All rights reserved

6-31

The Correctness of the Recursive


Factorial Method
Pseudocodeforarecursivemethodthatcomputes
thefactorialofanonnegativeintegern
fact(n)
if (n is 0) {
return 1
}
else {
return n * fact(n 1)
}

2006 Pearson Addison-Wesley. All rights reserved

6-32

The Correctness of the Recursive


Factorial Method
Inductiononncanprovethatthemethodfact
returnsthevalues
fact(0)=0!=1
fact(n)=n!=n*(n1)*(n2)**1ifn>0

2006 Pearson Addison-Wesley. All rights reserved

6-33

The Cost of Towers of Hanoi


SolutiontotheTowersofHanoiproblem
solveTowers(count, source, destination, spare)
if (count is 1) {
Move a disk directly from source to destination
}
else {
solveTowers(count-1, source, spare, destination)
solveTowers(1, source, destination, spare)
solveTowers(count-1, spare, destination, source)
}

2006 Pearson Addison-Wesley. All rights reserved

6-34

The Cost of Towers of Hanoi


Question
IfyoubeginwithNdisks,howmanymovesdoes
solveTowersmaketosolvetheproblem?

Let
moves(N)bethenumberofmovesmadestartingwith
Ndisks

WhenN=1
moves(1)=1

2006 Pearson Addison-Wesley. All rights reserved

6-35

The Cost of Towers of Hanoi


WhenN>1
moves(N)=moves(N1)+moves(1)+moves(N1)

Recurrencerelationforthenumberofmovesthat
solveTowersrequiresforNdisks
moves(1)=1
moves(N)=2*moves(N1)+1

2006 Pearson Addison-Wesley. All rights reserved

ifN>1

6-36

The Cost of Towers of Hanoi


Aclosedformformulaforthenumberofmoves
thatsolveTowersrequiresforNdisks
moves(N)=2N1,forallN1
InductiononNcanprovidetheproofthat
moves(N)=2N1

2006 Pearson Addison-Wesley. All rights reserved

6-37

Summary
Backtrackingisasolutionstrategythatinvolves
bothrecursionandasequenceofguessesthat
ultimatelyleadtoasolution
Agrammarisadevicefordefiningalanguage
Alanguageisasetofstringsofsymbols
Arecognitionalgorithmforalanguagecanoftenbe
baseddirectlyonthegrammarofthelanguage
Grammarsarefrequentlyrecursive

2006 Pearson Addison-Wesley. All rights reserved

6-38

Summary
Differentlanguagesofalgebraicexpressionshave
theirrelativeadvantagesanddisadvantages
Prefixexpressions
Postfixexpressions
Infixexpressions

Acloserelationshipexistsbetweenmathematical
inductionandrecursion
Inductioncanbeusedtoprovepropertiesabouta
recursivealgorithm
2006 Pearson Addison-Wesley. All rights reserved

6-39

You might also like