Chapter 23 - Recursion revisited. After you have mastered the material in this chapter, you will be able to: Take a fresh look at recursion, learn when to use recursion and when to stay away from it, learn to prove the correctness of recursive methods, get ready for the Game of Hex lab.
Trang 1and Data Structures
Maria Litvin ● Gary Litvin
2nd AP edition with GridWorld
Trang 2Objectives:
• Take a fresh look at recursion
• Learn when to use recursion and when to stay away from it
• Learn to prove the correctness of recursive methods
• Get ready for the Game of Hex lab
Trang 3Recursion Basics
• A recursive method has a base case (or
several base cases) and a recursive case
for a “smaller” task
• Recursive calls must eventually converge to a base case, when recursion stops
Trang 4A
Append the first char
DCBA
Take substring
Base case(nothing to do)
Recursive case
Trang 5Caution: NOTdouble y = pow(x, n / 2) *pow(x, n / 2);
Trang 7Example 4
public boolean degreeOfSeparation (
Set<Person> people, Person p1, Person p2, int n)
p1
p2p
Trang 8When to Use Recursion
• Recursion is especially useful for handling nested structures and branching processes
Trang 10ABCD DCA BCDA B
CAD B ACD B DAC B ADC B
ABCD BDA CDBA C
DAB C ADB C BAD C ABD C
ABCD
BCA D CBA D CAB D ACB D BAC D ABC D
Trang 11Use Recursion
• When it significantly simplifies code
without significant perfomance penalty
Do Not Use Recursion
• When a method allocates large local arrays
• When a method unpredictably changes fields
• When iterative solutions is just as simple
Trang 12Just As Easy With Iterations
public String reverse (String s)
Trang 13Not Easy Without Recursion
public void traverse (TreeNode root)
Need your own stack to do this without recursion
Trang 14Very Inefficient Recursive Code
public long fibonacci (int n)
{ next = f1 + f2;
f1 = f2;
f2 = next;
n ;
} return f2;
Trang 15Recursion and Math Induction
• Recursive methods are hard to trace in a
conventional way.
• A recursive method can be proven correct using math induction.
• Other properties of a recursive method
(running time, required space, etc.) can be obtained by using math induction.
Trang 16Math Induction Basics
• You have a sequence of statements
P1, P2, P3, Pn-1 , Pn ,
• Suppose P1 is true (“base case”).
• Suppose you can prove that for any n > 1, if
P1, Pn-1 are all true then Pn must be true, too.
• Then you can conclude (“by math induction”)
that Pn is true for any n 1
It is often possible to prove that if P n-1
is true then P n is also true
Trang 17Math Induction Example:
Prove that for any n 1
Trang 18Math Induction and Recursion
public String reverse (String s)
Let us verify that this method works, that is, reverse(s)
indeed returns the reverse of s We will use math
induction “over the length of s.”
To be continued
Trang 192 Suppose (induction hypothesis)
reverse works for any string of length
n-1 Then it works for s.substring(1).
So we reverse that substring and then
append the first char of s at the end.
We get the reverse of s.
By math induction, reverse works for
a string of any length, q.e.d
public String reverse (String s) {
if (s.length < 2) return s;
return reverse (s.substring(1)) + s.charAt(0);
}
Trang 20The Tower of Hanoi
• Objective: move the tower from one peg to another, moving one disk at a time and
never placing a larger disk on top of a
smaller one; you can use the spare peg.
• This puzzle was invented by François
Edouard Anatole Lucas and published in 1883
Trang 21The Tower of Hanoi: Recursive Solution
For n disks:
disk to the desired peg.
• If n > 1
to a spare peg (recursive
step)
the desired peg
the spare to the desired
peg (recursive step)
Trang 22The Game of Hex
• Two players take turns placing a stone of their color
• Objective: connect your pair of the opposite sides of the board with stones of your color
Trang 23The Game of Hex (cont’d)
• Computer representation of the board
in a 2-D array
Trang 24The Game of Hex (cont’d)
• To detect a win, determine whether any
“blob” (connected group of stones)
touches the opposite sides
Trang 25The Game of Hex (cont’d)
• This kind of task falls into the category of
“area fill” tasks
Trang 26• What kinds of applications especially
benefit from recursion?
• Give an example of a task that can be
programmed recursively and also, as
easily, with iterations.
Trang 28Review (cont’d):
• What is the number of moves necessary
to solve the Tower of Hanoi puzzle with
1, 2, 3, , n disks? How would you prove
your hypothesis?
• Can you come up with an idea for a
recursive algorithm for “area fill”?