College of Computing & Information Technology
King Abdulaziz University
CPCS-204 – Data Structures I
More Recursion
More Recursion page 2
© Dr. Jonathan (Yahya) Cazalas
Recursion
 What is Recursion? (reminder from last time)
 From the programming perspective:
 Recursion solves large problems by reducing
them to smaller problems of the same form
 Recursion is a method that invokes itself
 Basically splits a problem into one or more SIMPLER
versions of itself
 And we must have a way of stopping the recursion
 So the method must have some sort of calls or
conditional statements that can actually terminate the
method
More Recursion page 3
© Dr. Jonathan (Yahya) Cazalas
Recursion - Factorial
 Example: Compute Factorial of a Number
 What is a factorial?
 4! = 4 * 3 * 2 * 1 = 24
 In general, we can say:
 n! = n * (n-1) * (n-2) * … * 2 * 1
 Also, 0! = 1
 (just accept it!)
More Recursion page 4
© Dr. Jonathan (Yahya) Cazalas
Recursion - Factorial
 Example: Compute Factorial of a Number
 Recursive Solution
 Mathematically, factorial is already defined recursively
 Note that each factorial is related to a factorial of the
next smaller integer
 4! = 4*3*2*1
 Right?
 Another example:
 10! = 10*9*8*7*6*5*4*3*2*1
 10! = 10*
= 4 * (4-1)! = 4 * (3!)
(9!) This is clear right?
Since 9! clearly is equal to
9*8*7*6*5*4*3*2*1
More Recursion page 5
© Dr. Jonathan (Yahya) Cazalas
Recursion - Factorial
 Example: Compute Factorial of a Number
 Recursive Solution
 Mathematically, factorial is already defined recursively
 Note that each factorial is related to a factorial of the next
smaller integer
 Now we can say, in general, that:
 n! = n * (n-1)!
 But we need something else
 We need a stopping case, or this will just go on and on and on
 NOT good!
 We let 0! = 1
 So in “math terms”, we say
 n! = 1 if n = 0
 n! = n * (n-1)! if n > 0
More Recursion page 6
© Dr. Jonathan (Yahya) Cazalas
Recursion - Factorial
 How do we do this recursively?
 We need a method that we will call
 And this method will then call itself (recursively)
 until the stopping case (n == 0)
 When this method is called with 10 as the parameter, it
prints the result of 10*9*8*7*6*5*4*3*2*1:
 3628800
public static int factorial(int n) {
if (n == 0)
return 1;
else
return (n * factorial(n – 1));
}
More Recursion page 7
© Dr. Jonathan (Yahya) Cazalas
Recursion - Factorial
 Here’s what’s going on…in pictures
public static void main(String[] args) {
int F = factorial(10);
System.out.println(F);
}
factorial(10)
Returns (10*factorial(9))
factorial(9)
Returns (9*factorial(8))
factorial(8)
Returns (8*factorial(7))
factorial(7)
Returns (7*factorial(6))
factorial(6)
Returns (6*factorial(5))
factorial(5)
Returns (5*factorial(4))
factorial(4)
Returns (4*factorial(3))
factorial(3)
Returns (3*factorial(2))
factorial(2)
Returns (2*factorial(1))
factorial(1)
Returns (1*factorial(0))
factorial(0)
Returns 1
More Recursion page 8
© Dr. Jonathan (Yahya) Cazalas
Recursion - Factorial
 Here’s what’s going on…in pictures
 So now when we return,
 Where do we return to?
 We return to the method that called factorial(0)
 We return the value, 1, into the spot that called factorial(0)
factorial(10)
Returns (10*factorial(9))
factorial(9)
Returns (9*factorial(8))
factorial(8)
Returns (8*factorial(7))
factorial(7)
Returns (7*factorial(6))
factorial(6)
Returns (6*factorial(5))
factorial(5)
Returns (5*factorial(4))
factorial(4)
Returns (4*factorial(3))
factorial(3)
Returns (3*factorial(2))
factorial(2)
Returns (2*factorial(1))
factorial(1)
Returns (1*factorial(0))
factorial(0)
Returns 1
public static void main(String[] args) {
int F = factorial(10);
System.out.println(F);
}
More Recursion page 9
© Dr. Jonathan (Yahya) Cazalas
public static void main(String[] args) {
int F = factorial(10);
System.out.println(F);
}
Recursion - Factorial
 Here’s what’s going on…in pictures
 Now factorial has the value 3,628,800.
factorial(10)
Returns (10*factorial(9))
factorial(9)
Returns (9*factorial(8))
factorial(8)
Returns (8*factorial(7))
factorial(7)
Returns (7*factorial(6))
factorial(6)
Returns (6*factorial(5))
factorial(5)
Returns (5*factorial(4))
factorial(4)
Returns (4*factorial(3))
factorial(3)
Returns (3*factorial(2))
factorial(2)
Returns (2*factorial(1))
factorial(1)
Returns (1*factorial(0))
factorial(0)
Returns 1
factorial(1)
Returns (1*1)
factorial(2)
Returns (2*1)
factorial(3)
Returns (3*2)
factorial(4)
Returns (4*6)
factorial(5)
Returns (5*24)
factorial(6)
Returns (6*120)
factorial(7)
Returns (7*720)
factorial(8)
Returns (8*5040)
factorial(9)
Returns (9*40320)
factorial(10)
Returns (10*362880)
1
1
2
6
24
120
720
5040
40320
362880
3628800
More Recursion page 10
© Dr. Jonathan (Yahya) Cazalas
Recursion: General Structure
 General Structure of Recursive methods:
 What we can determine from previous examples:
 When we have a problem, we want to break it into
chunks
 Where one of the chunks is a smaller version of the
same problem
 Factorial Example:
 We utilized the fact that n! = n*(n-1)!
 And we realized that (n-1)! is, in essence, an easier
version of the original problem
 Right?
 We all should agree that 9! is a bit easier than 10!
More Recursion page 11
© Dr. Jonathan (Yahya) Cazalas
Recursion: General Structure
 General Structure of Recursive methods:
 What we can determine from previous examples:
 Eventually, we break down our original problem to such
an extent that the small sub-problem becomes quite
easy to solve
 At this point, we don’t make more recursive calls
 Rather, we directly return the answer
 Or complete whatever task we are doing
 This allows us to think about a general structure
of a recursive method
More Recursion page 12
© Dr. Jonathan (Yahya) Cazalas
Recursion: General Structure
 General Structure of Recursive methods:
 Basic structure has 2 main options:
1) Break down the problem further
 Into a smaller sub-problem
2) OR, the problem is small enough on its own
 Solve it
 In programming, when we have two options, we
us an if statement
 So here are our two constructs of recursive
methods…
More Recursion page 13
© Dr. Jonathan (Yahya) Cazalas
Recursion: General Structure
 General Structure of Recursive methods:
 2 general constructs:
 Construct 1:
 methods that return values take on this construct
if (terminating condition) {
DO FINAL ACTION
}
else {
Take one step closer to terminating condition
Call method RECURSIVELY on smaller subproblem
}
More Recursion page 14
© Dr. Jonathan (Yahya) Cazalas
Recursion: General Structure
 General Structure of Recursive methods:
 2 general constructs:
 Construct 2:
 void recursive methods use this construct
if (!(terminating condition) ) {
Take a step closer to terminating condition
Call method RECURSIVELY on smaller subproblem
}
More Recursion page 15
© Dr. Jonathan (Yahya) Cazalas
Recursion: General Structure
 Example using Construct 1
 Our method (Sum Integers):
 Takes in one positive integer parameter, n
 Returns the sum 1+2+…+n
 So our recursive method must sum all the integers up
until (and including) n
 How do we do this recursively?
 We need to solve this in such a way that part of the
solution is a sub-problem of the EXACT same nature of
the original problem.
More Recursion page 16
© Dr. Jonathan (Yahya) Cazalas
Recursion: General Structure
 Example using Construct 1
 Our method:
 Using n as the input, we define the following function
 f(n) = 1 + 2 + 3 + … + n
 Hopefully it is clear that this is our desired function
 Example:
 f(10) = 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10
 So the question is:
 Given this function, f(n), how do we make it
recursive???
More Recursion page 17
© Dr. Jonathan (Yahya) Cazalas
Recursion: General Structure
 Example using Construct 1
 Our method:
 Using n as the input, we define the following function
 f(n) = 1 + 2 + 3 + … + n
 REMEMBER:
 We want a method that solves this same problem
 But we want that problem to be recursive:
 It should solve f(n) by reducing it to a smaller problem, but of
the same form
 Just like the factorial example: n! = n * (n-1)!
 (n-1)! was a smaller form of n!
 So think, what is a “smaller form” of our function, f(n)
More Recursion page 18
© Dr. Jonathan (Yahya) Cazalas
Recursion: General Structure
 Example using Construct 1
 Our function:
 Using n as the input, we define the following function
 f(n) = 1 + 2 + 3 + … + n
 So to make this recursive, can we say:
 f(n) = 1 + (2 + 3 + … + n)
 Does that “look” recursive?
 Is there a sub-problem that is the EXACT same form as
the original problem?
 NO!
 2+3+…+n is NOT a sub-problem of the form 1+2+…+n
?
More Recursion page 19
© Dr. Jonathan (Yahya) Cazalas
Recursion: General Structure
 Example using Construct 1
 Our function:
 Using n as the input, we get the following function
 f(n) = 1 + 2 + 3 + … + n
 Let’s now try this:
 f(n) = 1 + 2 + … + n
 AAAHHH.
 Here we have an expression
 1 + 2 + … + (n-1)
 which IS indeed a sub-problem of the same form
= n + (1 + 2 + … + (n-1))
More Recursion page 20
© Dr. Jonathan (Yahya) Cazalas
Recursion: General Structure
 Example using Construct 1
 Our function:
 Using n as the input, we get the following function
 f(n) = 1 + 2 + 3 + … + n
 So now we have:
 f(n) = 1 + 2 + … + n = n + (1 + 2 + … + (n-1))
 Now, realize the following:
 Use an example:
 f(10) = 1 + 2 + … + 10
 And what is (1 + 2 + … + 9)?
 So look at what we can say:
 We can say that, f(10) = 10 + f(9)
It is f(9)!
= 10 + (1 + 2 + … + 9)
More Recursion page 21
© Dr. Jonathan (Yahya) Cazalas
Recursion: General Structure
 Example using Construct 1
 Our function:
 Using n as the input, we get the following function
 f(n) = 1 + 2 + 3 + … + n
 So now we have:
 f(n) = 1 + 2 + … + n = n + (1 + 2 + … + (n-1))
 Now, realize the following:
 So, in general, we have: f(n) = n + f(n-1)
 Right?
 Just like f(10) = 10 + f(9)
 So, we’ve defined our function, f(n), to be in terms of
a smaller version of itself…in terms of f(n-1)
More Recursion page 22
© Dr. Jonathan (Yahya) Cazalas
Recursion: General Structure
 Example using Construct 1
 Our function:
 Using n as the input, we get the following function
 f(n) = 1 + 2 + 3 + … + n
 So now we have:
 f(n) = 1 + 2 + … + n = n + (1 + 2 + … + (n-1))
 Now, realize the following:
 So here is our function, defined recursively
 f(n) = n + f(n-1)
More Recursion page 23
© Dr. Jonathan (Yahya) Cazalas
Recursion: General Structure
 Example using Construct 1
 Our function (now recursive):
 f(n) = n + f(n-1)
 Reminder of construct 1:
if (terminating condition) {
DO FINAL ACTION
}
else {
Take one step closer to terminating condition
Call method RECURSIVELY on smaller subproblem
}
More Recursion page 24
© Dr. Jonathan (Yahya) Cazalas
Recursion: General Structure
 Example using Construct 1
 Our function:
 f(n) = n + f(n-1)
 Reminder of construct 1:
 So we need to determine the terminating condition!
 We know that f(0) = 0
 So our terminating condition can be n = 0
 Additionally, our recursive calls need to return an
expression for f(n) in terms of f(k)
 for some k < n
 We just found that f(n) = n + f(n-1)
 So now we can write our actual method…
More Recursion page 25
© Dr. Jonathan (Yahya) Cazalas
Recursion: General Structure
 Example using Construct 1
 Our function: f(n) = n + f(n-1)
// Pre-condition: n is a positive int
// Post-condition: method returns the sum
// 1 + 2 + ... + n
public static int sumNumbers(int n) {
if ( n == 0 )
return 0;
else
return (n + sumNumbers(n-1));
}
More Recursion page 26
© Dr. Jonathan (Yahya) Cazalas
Recursion: General Structure
 Another example using Construct 1
 Our method:
 Calculates be
 Some base raised to a power, e
 The input is the base, b, and the exponent, e
 So if the input was 2 for the base and 4 for the exponent
 The answer would be 24 = 16
 How do we do this recursively?
 We need to solve this in such a way that part of the
solution is a sub-problem of the EXACT same nature of
the original problem.
More Recursion page 27
© Dr. Jonathan (Yahya) Cazalas
Recursion: General Structure
 Another example using Construct 1
 Our method:
 Using b and e as input, here is our function
 f(b,e) = be
 So to make this recursive, can we say:
 f(b,e) = be = b*b(e-1)
 Does that “look” recursive?
 YES it does!
 Why?
 Cuz the right side is indeed a sub-problem of the original
 We want to evaluate be
 And our right side evaluates b(e-1)
Example with numbers:
f(2,4) = 24 = 2*23
---So we solve the larger
problem (24) by reducing it to
a smaller problem (23).
More Recursion page 28
© Dr. Jonathan (Yahya) Cazalas
Recursion: General Structure
 Another example using Construct 1
 Our method:
 f(b,e) = b*b(e-1)
 Reminder of construct 1:
if (terminating condition) {
DO FINAL ACTION
}
else {
Take one step closer to terminating condition
Call method RECURSIVELY on smaller subproblem
}
More Recursion page 29
© Dr. Jonathan (Yahya) Cazalas
Recursion: General Structure
 Another example using Construct 1
 Our method:
 f(b,e) = b*b(e-1)
 Reminder of construct 1:
 So we need to determine the terminating condition!
 We know that f(b,0) = b0 = 1
 So our terminating condition can be when e = 0
 Additionally, our recursive calls need to return an
expression for f(b,e) in terms of f(b,k)
 for some k < e
 We just found that f(b,e) = b*b(e-1)
 So now we can write our actual method…
More Recursion page 30
© Dr. Jonathan (Yahya) Cazalas
Recursion: General Structure
 Another example using Construct 1
 Our method:
// Pre-conditions: e is greater than or equal to 0.
// Post-conditions: returns be.
public static int Power(int base, int exponent) {
if ( exponent == 0 )
return 1;
else
return (base*Power(base, exponent-1));
}
More Recursion page 31
© Dr. Jonathan (Yahya) Cazalas
Recursion: General Structure
 Example using Construct 2
 Remember the construct:
 This is used when the return type is void
if (!(terminating condition) ) {
Take a step closer to terminating condition
Call method RECURSIVELY on smaller subproblem
}
More Recursion page 32
© Dr. Jonathan (Yahya) Cazalas
Recursion: General Structure
 Example using Construct 2
 Our method: Reverse a String
 Takes in a string (character array)
 The method simply prints the string in REVERSE order
 So what is the terminating condition?
 We will print the string, in reverse order, character by
character
 So we terminate when there are no more characters left
to print
 The 2nd argument to the method (length) will be reduced
until it is 0 (showing no more characters left to print)
More Recursion page 33
© Dr. Jonathan (Yahya) Cazalas
Recursion: General Structure
 Example using Construct 2
 Our method:
 What’s going on:
 If the string is ever null or if the length is < 1 (zero)
 Return!
 Else, we have TWO statements that get executed
public static void printCharsReverse(String str) {
if (str == null || str.length() < 1)
return;
else {
printCharsReverse(str.substring(1));
System.out.print(str.charAt(0));
}
}
More Recursion page 34
© Dr. Jonathan (Yahya) Cazalas
Recursion: General Structure
 Example using Construct 2
 Our method:
 What’s going on:
1) printCharsReverse recursively calls the method
 The parameter is a substring of the original string
 The substring will start from index 1 of the original string
2) The 2nd statement prints the character at index 0
public static void printCharsReverse(String str) {
if (str == null || str.length() < 1)
return;
else {
printCharsReverse(str.substring(1));
System.out.print(str.charAt(0));
}
}
More Recursion page 35
© Dr. Jonathan (Yahya) Cazalas
Recursion: General Structure
 Example using Construct 2
 Our method:
 What’s going on:
 Let’s say the string in str is “computer”
 The result of str.substring(1) will be “omputer”
 So the string “omputer” is sent as a parameter to the
recursively called method
public static void printCharsReverse(String str) {
if (str == null || str.length() < 1)
return;
else {
printCharsReverse(str.substring(1));
System.out.print(str.charAt(0));
}
}
More Recursion page 36
© Dr. Jonathan (Yahya) Cazalas
Recursion: General Structure
 Example using Construct 2
 Our method:
 What’s going on:
 Notice: until now, we did NOT execute the print
statement
 This statement must WAIT until printCharsReverse
finishes
public static void printCharsReverse(String str) {
if (str == null || str.length() < 1)
return;
else {
printCharsReverse(str.substring(1));
System.out.print(str.charAt(0));
}
}
More Recursion page 37
© Dr. Jonathan (Yahya) Cazalas
Recursion: General Structure
 Example using Construct 2
 Our method:
 What’s going on:
 So now a new method (second method) opens up with
“omputer” as the parameter, str
 str is not null and the length is not less than 1
 So we enter the else statement
public static void printCharsReverse(String str) {
if (str == null || str.length() < 1)
return;
else {
printCharsReverse(str.substring(1));
System.out.print(str.charAt(0));
}
}
More Recursion page 38
© Dr. Jonathan (Yahya) Cazalas
Recursion: General Structure
 Example using Construct 2
 Our method:
 What’s going on:
 The 1st command is to recursively call our method
 Again, the parameter is a substring starting at index 1
 So now, the parameter sent will be “mputer”
 We execute the 1st command and recursively call our method
public static void printCharsReverse(String str) {
if (str == null || str.length() < 1)
return;
else {
printCharsReverse(str.substring(1));
System.out.print(str.charAt(0));
}
}
More Recursion page 39
© Dr. Jonathan (Yahya) Cazalas
Recursion: General Structure
 Example using Construct 2
 Our method:
 What’s going on:
 Again, the 2nd command (the print statement) must wait
for the 1st command (the recursive call) to finish before it
can execute (print)
public static void printCharsReverse(String str) {
if (str == null || str.length() < 1)
return;
else {
printCharsReverse(str.substring(1));
System.out.print(str.charAt(0));
}
}
More Recursion page 40
© Dr. Jonathan (Yahya) Cazalas
Recursion: General Structure
 Example using Construct 2
 Our method:
 What’s going on:
 A new method (third method) opens up with “mputer” as
the parameter, str
 str is not null and the length is not less than 1
 So we enter the else statement
public static void printCharsReverse(String str) {
if (str == null || str.length() < 1)
return;
else {
printCharsReverse(str.substring(1));
System.out.print(str.charAt(0));
}
}
More Recursion page 41
© Dr. Jonathan (Yahya) Cazalas
Recursion: General Structure
 Example using Construct 2
 Our method:
 What’s going on:
 Again we recursively call our method
 This time with the parameter “puter”
 And again, the 2nd command (the print statement) must
wait until the 1st command (recursion) finishes
public static void printCharsReverse(String str) {
if (str == null || str.length() < 1)
return;
else {
printCharsReverse(str.substring(1));
System.out.print(str.charAt(0));
}
}
More Recursion page 42
© Dr. Jonathan (Yahya) Cazalas
Recursion: General Structure
 Example using Construct 2
 Our method:
 What’s going on:
 At some point, our string, str, will be reduced to only
one letter, the last letter (“r”)
 This string is not null and the length is not less than zero
 So for one final time, we enter the else statement
public static void printCharsReverse(String str) {
if (str == null || str.length() < 1)
return;
else {
printCharsReverse(str.substring(1));
System.out.print(str.charAt(0));
}
}
More Recursion page 43
© Dr. Jonathan (Yahya) Cazalas
Recursion: General Structure
 Example using Construct 2
 Our method:
 What’s going on:
 We will recursively call our method with a substring of “r”
 The resulting substring will be empty (its length will be < 1)
 Therefore, the recursive call will enter into the IF statement
 And it will return to the previous step of the recursion
public static void printCharsReverse(String str) {
if (str == null || str.length() < 1)
return;
else {
printCharsReverse(str.substring(1));
System.out.print(str.charAt(0));
}
}
More Recursion page 44
© Dr. Jonathan (Yahya) Cazalas
Recursion: General Structure
 Example using Construct 2
 Our method:
 What’s going on:
 Now that we finally reached the terminating condition,
we can return back to each of the recursive methods
 As we return back, NOW we finally PRINT
 Now we can execute the print statement
public static void printCharsReverse(String str) {
if (str == null || str.length() < 1)
return;
else {
printCharsReverse(str.substring(1));
System.out.print(str.charAt(0));
}
}
More Recursion page 45
© Dr. Jonathan (Yahya) Cazalas
Recursion: General Structure
 Example using Construct 2
 Our method:
 What’s going on:
 So as we return back through the open recursive methods
 We print “r”
 Then we print “e”
 Then we print “t” … and so on
public static void printCharsReverse(String str) {
if (str == null || str.length() < 1)
return;
else {
printCharsReverse(str.substring(1));
System.out.print(str.charAt(0));
}
}
More Recursion page 46
© Dr. Jonathan (Yahya) Cazalas
Recursion: General Structure
 Example using Construct 2
 Our method:
 What’s going on:
 Will we have printed: r e t u p m o
 And then we return to the original recursive method
 At that point, we print a “c”, resulting in:
 r e t u p m o c
public static void printCharsReverse(String str) {
if (str == null || str.length() < 1)
return;
else {
printCharsReverse(str.substring(1));
System.out.print(str.charAt(0));
}
}
More Recursion page 47
© Dr. Jonathan (Yahya) Cazalas
Brief Interlude: Human Stupidity
More Recursion page 48
© Dr. Jonathan (Yahya) Cazalas
Recursion – Practice Problem
 Practice Problem:
 Write a recursive method that:
 Takes in two non-negative integer parameters
 Returns the product of these parameters
 But it does NOT use multiplication to get the answer
 So if the parameters are 6 and 4
 The answer would be 24
 How do we do this not actually using multiplication
 What another way of saying 6*4?
 We are adding 6, 4 times!
 6*4 = 6 + 6 + 6 + 6
 So now think of your method…
More Recursion page 49
© Dr. Jonathan (Yahya) Cazalas
Recursion – Practice Problem
 Practice Problem:
 Solution:
// Precondition: Both parameters are
// non-negative integers.
// Postcondition: The product of the two
// parameters is returned.
public static int Multiply(int first, int second) {
if (( second == 0 ) || ( first = 0 ))
return 0;
else
return (first + Multiply(first, second-1));
}
More Recursion page 50
© Dr. Jonathan (Yahya) Cazalas
Recursion – Towers of Hanoi
 Towers of Hanoi:
 Here’s the problem:
 There are three vertical poles
 There are 64 disks on tower 1 (left most tower)
 The disks are arranged with the largest diameter disks at
the bottom
 Some monk has the daunting task of moving disks
from one tower to another tower
 Often defined as moving from Tower #1 to Tower #3
 Tower #2 is just an intermediate pole
 He can only move ONE disk at a time
 And he MUST follow the rule of NEVER putting a bigger
disk on top of a smaller disk
More Recursion page 51
© Dr. Jonathan (Yahya) Cazalas
Recursion – Towers of Hanoi
 Towers of Hanoi:
 Solution:
 We must find a recursive strategy
 Thoughts:
 Any tower with more than one disk must clearly be moved
in pieces
 If there is just one disk on a pole, then we move it
start temp finish
More Recursion page 52
© Dr. Jonathan (Yahya) Cazalas
Recursion – Towers of Hanoi
 Towers of Hanoi:
 Solution:
 Irrespective of the number of disks, the following steps
MUST be carried out:
 The bottom disk needs to move to the destination tower
1) So step 1 must be to move all disks above the bottom
disk to the intermediate tower
2) In step 2, the bottom disk can now be moved to the
destination tower
3) In step 3, the disks that were initially above the bottom
disk must now be put back on top
 Of course, at the destination
 Let’s look at the situation with only 3 disks…
More Recursion page 53
© Dr. Jonathan (Yahya) Cazalas
Recursion – Towers of Hanoi
 Towers of Hanoi:
 Solution:
 Step 1:
 Move 2 disks from start to temp using finish Tower.
 To understand the recursive routine, let us assume that we
know how to solve 2 disk problem, and go for the next
step.
 Meaning, we “know” how to move 2 disks appropriately
start temp finish start temp finish
More Recursion page 54
© Dr. Jonathan (Yahya) Cazalas
start temp finish start temp finish
Recursion – Towers of Hanoi
 Towers of Hanoi:
 Solution:
 Step 2:
 Move the (remaining) single disk from start to finish
 This does not involve recursion
 and can be carried out without using temp tower.
 In our program, this is just a print statement
 Showing what we moved and to where
More Recursion page 55
© Dr. Jonathan (Yahya) Cazalas
start temp finish
 Towers of Hanoi:
 Solution:
 Step 3:
 Now we are at the last step of the routine.
 Move the 2 disks from temp tower to finish tower using the
start tower
 This is also done recursively
start temp finish
Recursion – Towers of Hanoi
More Recursion page 56
© Dr. Jonathan (Yahya) Cazalas
start temp finish
start
start temp finish
1
start temp finish
2
start temp finish
3
start temp finish
4
Recursion – Towers of Hanoi
More Recursion page 57
© Dr. Jonathan (Yahya) Cazalas
start temp finish
6
start temp finish
start temp finish
5
7
Recursion – Towers of Hanoi
 # of steps needed:
 We had 3 disks requiring seven steps
 4 disks would require 15 steps
 n disks would require 2n -1 steps
 HUGE number
More Recursion page 58
© Dr. Jonathan (Yahya) Cazalas
 Towers of Hanoi:
 Solution:
 Search in your book!
Recursion – Towers of Hanoi
More Recursion page 59
© Dr. Jonathan (Yahya) Cazalas
Recursion
WASN’T
THAT
ENCHANTING!
More Recursion page 60
© Dr. Jonathan (Yahya) Cazalas
Daily Demotivator
College of Computing & Information Technology
King Abdulaziz University
CPCS-204 – Data Structures I
More Recursion

recursion2

  • 1.
    College of Computing& Information Technology King Abdulaziz University CPCS-204 – Data Structures I More Recursion
  • 2.
    More Recursion page2 © Dr. Jonathan (Yahya) Cazalas Recursion  What is Recursion? (reminder from last time)  From the programming perspective:  Recursion solves large problems by reducing them to smaller problems of the same form  Recursion is a method that invokes itself  Basically splits a problem into one or more SIMPLER versions of itself  And we must have a way of stopping the recursion  So the method must have some sort of calls or conditional statements that can actually terminate the method
  • 3.
    More Recursion page3 © Dr. Jonathan (Yahya) Cazalas Recursion - Factorial  Example: Compute Factorial of a Number  What is a factorial?  4! = 4 * 3 * 2 * 1 = 24  In general, we can say:  n! = n * (n-1) * (n-2) * … * 2 * 1  Also, 0! = 1  (just accept it!)
  • 4.
    More Recursion page4 © Dr. Jonathan (Yahya) Cazalas Recursion - Factorial  Example: Compute Factorial of a Number  Recursive Solution  Mathematically, factorial is already defined recursively  Note that each factorial is related to a factorial of the next smaller integer  4! = 4*3*2*1  Right?  Another example:  10! = 10*9*8*7*6*5*4*3*2*1  10! = 10* = 4 * (4-1)! = 4 * (3!) (9!) This is clear right? Since 9! clearly is equal to 9*8*7*6*5*4*3*2*1
  • 5.
    More Recursion page5 © Dr. Jonathan (Yahya) Cazalas Recursion - Factorial  Example: Compute Factorial of a Number  Recursive Solution  Mathematically, factorial is already defined recursively  Note that each factorial is related to a factorial of the next smaller integer  Now we can say, in general, that:  n! = n * (n-1)!  But we need something else  We need a stopping case, or this will just go on and on and on  NOT good!  We let 0! = 1  So in “math terms”, we say  n! = 1 if n = 0  n! = n * (n-1)! if n > 0
  • 6.
    More Recursion page6 © Dr. Jonathan (Yahya) Cazalas Recursion - Factorial  How do we do this recursively?  We need a method that we will call  And this method will then call itself (recursively)  until the stopping case (n == 0)  When this method is called with 10 as the parameter, it prints the result of 10*9*8*7*6*5*4*3*2*1:  3628800 public static int factorial(int n) { if (n == 0) return 1; else return (n * factorial(n – 1)); }
  • 7.
    More Recursion page7 © Dr. Jonathan (Yahya) Cazalas Recursion - Factorial  Here’s what’s going on…in pictures public static void main(String[] args) { int F = factorial(10); System.out.println(F); } factorial(10) Returns (10*factorial(9)) factorial(9) Returns (9*factorial(8)) factorial(8) Returns (8*factorial(7)) factorial(7) Returns (7*factorial(6)) factorial(6) Returns (6*factorial(5)) factorial(5) Returns (5*factorial(4)) factorial(4) Returns (4*factorial(3)) factorial(3) Returns (3*factorial(2)) factorial(2) Returns (2*factorial(1)) factorial(1) Returns (1*factorial(0)) factorial(0) Returns 1
  • 8.
    More Recursion page8 © Dr. Jonathan (Yahya) Cazalas Recursion - Factorial  Here’s what’s going on…in pictures  So now when we return,  Where do we return to?  We return to the method that called factorial(0)  We return the value, 1, into the spot that called factorial(0) factorial(10) Returns (10*factorial(9)) factorial(9) Returns (9*factorial(8)) factorial(8) Returns (8*factorial(7)) factorial(7) Returns (7*factorial(6)) factorial(6) Returns (6*factorial(5)) factorial(5) Returns (5*factorial(4)) factorial(4) Returns (4*factorial(3)) factorial(3) Returns (3*factorial(2)) factorial(2) Returns (2*factorial(1)) factorial(1) Returns (1*factorial(0)) factorial(0) Returns 1 public static void main(String[] args) { int F = factorial(10); System.out.println(F); }
  • 9.
    More Recursion page9 © Dr. Jonathan (Yahya) Cazalas public static void main(String[] args) { int F = factorial(10); System.out.println(F); } Recursion - Factorial  Here’s what’s going on…in pictures  Now factorial has the value 3,628,800. factorial(10) Returns (10*factorial(9)) factorial(9) Returns (9*factorial(8)) factorial(8) Returns (8*factorial(7)) factorial(7) Returns (7*factorial(6)) factorial(6) Returns (6*factorial(5)) factorial(5) Returns (5*factorial(4)) factorial(4) Returns (4*factorial(3)) factorial(3) Returns (3*factorial(2)) factorial(2) Returns (2*factorial(1)) factorial(1) Returns (1*factorial(0)) factorial(0) Returns 1 factorial(1) Returns (1*1) factorial(2) Returns (2*1) factorial(3) Returns (3*2) factorial(4) Returns (4*6) factorial(5) Returns (5*24) factorial(6) Returns (6*120) factorial(7) Returns (7*720) factorial(8) Returns (8*5040) factorial(9) Returns (9*40320) factorial(10) Returns (10*362880) 1 1 2 6 24 120 720 5040 40320 362880 3628800
  • 10.
    More Recursion page10 © Dr. Jonathan (Yahya) Cazalas Recursion: General Structure  General Structure of Recursive methods:  What we can determine from previous examples:  When we have a problem, we want to break it into chunks  Where one of the chunks is a smaller version of the same problem  Factorial Example:  We utilized the fact that n! = n*(n-1)!  And we realized that (n-1)! is, in essence, an easier version of the original problem  Right?  We all should agree that 9! is a bit easier than 10!
  • 11.
    More Recursion page11 © Dr. Jonathan (Yahya) Cazalas Recursion: General Structure  General Structure of Recursive methods:  What we can determine from previous examples:  Eventually, we break down our original problem to such an extent that the small sub-problem becomes quite easy to solve  At this point, we don’t make more recursive calls  Rather, we directly return the answer  Or complete whatever task we are doing  This allows us to think about a general structure of a recursive method
  • 12.
    More Recursion page12 © Dr. Jonathan (Yahya) Cazalas Recursion: General Structure  General Structure of Recursive methods:  Basic structure has 2 main options: 1) Break down the problem further  Into a smaller sub-problem 2) OR, the problem is small enough on its own  Solve it  In programming, when we have two options, we us an if statement  So here are our two constructs of recursive methods…
  • 13.
    More Recursion page13 © Dr. Jonathan (Yahya) Cazalas Recursion: General Structure  General Structure of Recursive methods:  2 general constructs:  Construct 1:  methods that return values take on this construct if (terminating condition) { DO FINAL ACTION } else { Take one step closer to terminating condition Call method RECURSIVELY on smaller subproblem }
  • 14.
    More Recursion page14 © Dr. Jonathan (Yahya) Cazalas Recursion: General Structure  General Structure of Recursive methods:  2 general constructs:  Construct 2:  void recursive methods use this construct if (!(terminating condition) ) { Take a step closer to terminating condition Call method RECURSIVELY on smaller subproblem }
  • 15.
    More Recursion page15 © Dr. Jonathan (Yahya) Cazalas Recursion: General Structure  Example using Construct 1  Our method (Sum Integers):  Takes in one positive integer parameter, n  Returns the sum 1+2+…+n  So our recursive method must sum all the integers up until (and including) n  How do we do this recursively?  We need to solve this in such a way that part of the solution is a sub-problem of the EXACT same nature of the original problem.
  • 16.
    More Recursion page16 © Dr. Jonathan (Yahya) Cazalas Recursion: General Structure  Example using Construct 1  Our method:  Using n as the input, we define the following function  f(n) = 1 + 2 + 3 + … + n  Hopefully it is clear that this is our desired function  Example:  f(10) = 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10  So the question is:  Given this function, f(n), how do we make it recursive???
  • 17.
    More Recursion page17 © Dr. Jonathan (Yahya) Cazalas Recursion: General Structure  Example using Construct 1  Our method:  Using n as the input, we define the following function  f(n) = 1 + 2 + 3 + … + n  REMEMBER:  We want a method that solves this same problem  But we want that problem to be recursive:  It should solve f(n) by reducing it to a smaller problem, but of the same form  Just like the factorial example: n! = n * (n-1)!  (n-1)! was a smaller form of n!  So think, what is a “smaller form” of our function, f(n)
  • 18.
    More Recursion page18 © Dr. Jonathan (Yahya) Cazalas Recursion: General Structure  Example using Construct 1  Our function:  Using n as the input, we define the following function  f(n) = 1 + 2 + 3 + … + n  So to make this recursive, can we say:  f(n) = 1 + (2 + 3 + … + n)  Does that “look” recursive?  Is there a sub-problem that is the EXACT same form as the original problem?  NO!  2+3+…+n is NOT a sub-problem of the form 1+2+…+n ?
  • 19.
    More Recursion page19 © Dr. Jonathan (Yahya) Cazalas Recursion: General Structure  Example using Construct 1  Our function:  Using n as the input, we get the following function  f(n) = 1 + 2 + 3 + … + n  Let’s now try this:  f(n) = 1 + 2 + … + n  AAAHHH.  Here we have an expression  1 + 2 + … + (n-1)  which IS indeed a sub-problem of the same form = n + (1 + 2 + … + (n-1))
  • 20.
    More Recursion page20 © Dr. Jonathan (Yahya) Cazalas Recursion: General Structure  Example using Construct 1  Our function:  Using n as the input, we get the following function  f(n) = 1 + 2 + 3 + … + n  So now we have:  f(n) = 1 + 2 + … + n = n + (1 + 2 + … + (n-1))  Now, realize the following:  Use an example:  f(10) = 1 + 2 + … + 10  And what is (1 + 2 + … + 9)?  So look at what we can say:  We can say that, f(10) = 10 + f(9) It is f(9)! = 10 + (1 + 2 + … + 9)
  • 21.
    More Recursion page21 © Dr. Jonathan (Yahya) Cazalas Recursion: General Structure  Example using Construct 1  Our function:  Using n as the input, we get the following function  f(n) = 1 + 2 + 3 + … + n  So now we have:  f(n) = 1 + 2 + … + n = n + (1 + 2 + … + (n-1))  Now, realize the following:  So, in general, we have: f(n) = n + f(n-1)  Right?  Just like f(10) = 10 + f(9)  So, we’ve defined our function, f(n), to be in terms of a smaller version of itself…in terms of f(n-1)
  • 22.
    More Recursion page22 © Dr. Jonathan (Yahya) Cazalas Recursion: General Structure  Example using Construct 1  Our function:  Using n as the input, we get the following function  f(n) = 1 + 2 + 3 + … + n  So now we have:  f(n) = 1 + 2 + … + n = n + (1 + 2 + … + (n-1))  Now, realize the following:  So here is our function, defined recursively  f(n) = n + f(n-1)
  • 23.
    More Recursion page23 © Dr. Jonathan (Yahya) Cazalas Recursion: General Structure  Example using Construct 1  Our function (now recursive):  f(n) = n + f(n-1)  Reminder of construct 1: if (terminating condition) { DO FINAL ACTION } else { Take one step closer to terminating condition Call method RECURSIVELY on smaller subproblem }
  • 24.
    More Recursion page24 © Dr. Jonathan (Yahya) Cazalas Recursion: General Structure  Example using Construct 1  Our function:  f(n) = n + f(n-1)  Reminder of construct 1:  So we need to determine the terminating condition!  We know that f(0) = 0  So our terminating condition can be n = 0  Additionally, our recursive calls need to return an expression for f(n) in terms of f(k)  for some k < n  We just found that f(n) = n + f(n-1)  So now we can write our actual method…
  • 25.
    More Recursion page25 © Dr. Jonathan (Yahya) Cazalas Recursion: General Structure  Example using Construct 1  Our function: f(n) = n + f(n-1) // Pre-condition: n is a positive int // Post-condition: method returns the sum // 1 + 2 + ... + n public static int sumNumbers(int n) { if ( n == 0 ) return 0; else return (n + sumNumbers(n-1)); }
  • 26.
    More Recursion page26 © Dr. Jonathan (Yahya) Cazalas Recursion: General Structure  Another example using Construct 1  Our method:  Calculates be  Some base raised to a power, e  The input is the base, b, and the exponent, e  So if the input was 2 for the base and 4 for the exponent  The answer would be 24 = 16  How do we do this recursively?  We need to solve this in such a way that part of the solution is a sub-problem of the EXACT same nature of the original problem.
  • 27.
    More Recursion page27 © Dr. Jonathan (Yahya) Cazalas Recursion: General Structure  Another example using Construct 1  Our method:  Using b and e as input, here is our function  f(b,e) = be  So to make this recursive, can we say:  f(b,e) = be = b*b(e-1)  Does that “look” recursive?  YES it does!  Why?  Cuz the right side is indeed a sub-problem of the original  We want to evaluate be  And our right side evaluates b(e-1) Example with numbers: f(2,4) = 24 = 2*23 ---So we solve the larger problem (24) by reducing it to a smaller problem (23).
  • 28.
    More Recursion page28 © Dr. Jonathan (Yahya) Cazalas Recursion: General Structure  Another example using Construct 1  Our method:  f(b,e) = b*b(e-1)  Reminder of construct 1: if (terminating condition) { DO FINAL ACTION } else { Take one step closer to terminating condition Call method RECURSIVELY on smaller subproblem }
  • 29.
    More Recursion page29 © Dr. Jonathan (Yahya) Cazalas Recursion: General Structure  Another example using Construct 1  Our method:  f(b,e) = b*b(e-1)  Reminder of construct 1:  So we need to determine the terminating condition!  We know that f(b,0) = b0 = 1  So our terminating condition can be when e = 0  Additionally, our recursive calls need to return an expression for f(b,e) in terms of f(b,k)  for some k < e  We just found that f(b,e) = b*b(e-1)  So now we can write our actual method…
  • 30.
    More Recursion page30 © Dr. Jonathan (Yahya) Cazalas Recursion: General Structure  Another example using Construct 1  Our method: // Pre-conditions: e is greater than or equal to 0. // Post-conditions: returns be. public static int Power(int base, int exponent) { if ( exponent == 0 ) return 1; else return (base*Power(base, exponent-1)); }
  • 31.
    More Recursion page31 © Dr. Jonathan (Yahya) Cazalas Recursion: General Structure  Example using Construct 2  Remember the construct:  This is used when the return type is void if (!(terminating condition) ) { Take a step closer to terminating condition Call method RECURSIVELY on smaller subproblem }
  • 32.
    More Recursion page32 © Dr. Jonathan (Yahya) Cazalas Recursion: General Structure  Example using Construct 2  Our method: Reverse a String  Takes in a string (character array)  The method simply prints the string in REVERSE order  So what is the terminating condition?  We will print the string, in reverse order, character by character  So we terminate when there are no more characters left to print  The 2nd argument to the method (length) will be reduced until it is 0 (showing no more characters left to print)
  • 33.
    More Recursion page33 © Dr. Jonathan (Yahya) Cazalas Recursion: General Structure  Example using Construct 2  Our method:  What’s going on:  If the string is ever null or if the length is < 1 (zero)  Return!  Else, we have TWO statements that get executed public static void printCharsReverse(String str) { if (str == null || str.length() < 1) return; else { printCharsReverse(str.substring(1)); System.out.print(str.charAt(0)); } }
  • 34.
    More Recursion page34 © Dr. Jonathan (Yahya) Cazalas Recursion: General Structure  Example using Construct 2  Our method:  What’s going on: 1) printCharsReverse recursively calls the method  The parameter is a substring of the original string  The substring will start from index 1 of the original string 2) The 2nd statement prints the character at index 0 public static void printCharsReverse(String str) { if (str == null || str.length() < 1) return; else { printCharsReverse(str.substring(1)); System.out.print(str.charAt(0)); } }
  • 35.
    More Recursion page35 © Dr. Jonathan (Yahya) Cazalas Recursion: General Structure  Example using Construct 2  Our method:  What’s going on:  Let’s say the string in str is “computer”  The result of str.substring(1) will be “omputer”  So the string “omputer” is sent as a parameter to the recursively called method public static void printCharsReverse(String str) { if (str == null || str.length() < 1) return; else { printCharsReverse(str.substring(1)); System.out.print(str.charAt(0)); } }
  • 36.
    More Recursion page36 © Dr. Jonathan (Yahya) Cazalas Recursion: General Structure  Example using Construct 2  Our method:  What’s going on:  Notice: until now, we did NOT execute the print statement  This statement must WAIT until printCharsReverse finishes public static void printCharsReverse(String str) { if (str == null || str.length() < 1) return; else { printCharsReverse(str.substring(1)); System.out.print(str.charAt(0)); } }
  • 37.
    More Recursion page37 © Dr. Jonathan (Yahya) Cazalas Recursion: General Structure  Example using Construct 2  Our method:  What’s going on:  So now a new method (second method) opens up with “omputer” as the parameter, str  str is not null and the length is not less than 1  So we enter the else statement public static void printCharsReverse(String str) { if (str == null || str.length() < 1) return; else { printCharsReverse(str.substring(1)); System.out.print(str.charAt(0)); } }
  • 38.
    More Recursion page38 © Dr. Jonathan (Yahya) Cazalas Recursion: General Structure  Example using Construct 2  Our method:  What’s going on:  The 1st command is to recursively call our method  Again, the parameter is a substring starting at index 1  So now, the parameter sent will be “mputer”  We execute the 1st command and recursively call our method public static void printCharsReverse(String str) { if (str == null || str.length() < 1) return; else { printCharsReverse(str.substring(1)); System.out.print(str.charAt(0)); } }
  • 39.
    More Recursion page39 © Dr. Jonathan (Yahya) Cazalas Recursion: General Structure  Example using Construct 2  Our method:  What’s going on:  Again, the 2nd command (the print statement) must wait for the 1st command (the recursive call) to finish before it can execute (print) public static void printCharsReverse(String str) { if (str == null || str.length() < 1) return; else { printCharsReverse(str.substring(1)); System.out.print(str.charAt(0)); } }
  • 40.
    More Recursion page40 © Dr. Jonathan (Yahya) Cazalas Recursion: General Structure  Example using Construct 2  Our method:  What’s going on:  A new method (third method) opens up with “mputer” as the parameter, str  str is not null and the length is not less than 1  So we enter the else statement public static void printCharsReverse(String str) { if (str == null || str.length() < 1) return; else { printCharsReverse(str.substring(1)); System.out.print(str.charAt(0)); } }
  • 41.
    More Recursion page41 © Dr. Jonathan (Yahya) Cazalas Recursion: General Structure  Example using Construct 2  Our method:  What’s going on:  Again we recursively call our method  This time with the parameter “puter”  And again, the 2nd command (the print statement) must wait until the 1st command (recursion) finishes public static void printCharsReverse(String str) { if (str == null || str.length() < 1) return; else { printCharsReverse(str.substring(1)); System.out.print(str.charAt(0)); } }
  • 42.
    More Recursion page42 © Dr. Jonathan (Yahya) Cazalas Recursion: General Structure  Example using Construct 2  Our method:  What’s going on:  At some point, our string, str, will be reduced to only one letter, the last letter (“r”)  This string is not null and the length is not less than zero  So for one final time, we enter the else statement public static void printCharsReverse(String str) { if (str == null || str.length() < 1) return; else { printCharsReverse(str.substring(1)); System.out.print(str.charAt(0)); } }
  • 43.
    More Recursion page43 © Dr. Jonathan (Yahya) Cazalas Recursion: General Structure  Example using Construct 2  Our method:  What’s going on:  We will recursively call our method with a substring of “r”  The resulting substring will be empty (its length will be < 1)  Therefore, the recursive call will enter into the IF statement  And it will return to the previous step of the recursion public static void printCharsReverse(String str) { if (str == null || str.length() < 1) return; else { printCharsReverse(str.substring(1)); System.out.print(str.charAt(0)); } }
  • 44.
    More Recursion page44 © Dr. Jonathan (Yahya) Cazalas Recursion: General Structure  Example using Construct 2  Our method:  What’s going on:  Now that we finally reached the terminating condition, we can return back to each of the recursive methods  As we return back, NOW we finally PRINT  Now we can execute the print statement public static void printCharsReverse(String str) { if (str == null || str.length() < 1) return; else { printCharsReverse(str.substring(1)); System.out.print(str.charAt(0)); } }
  • 45.
    More Recursion page45 © Dr. Jonathan (Yahya) Cazalas Recursion: General Structure  Example using Construct 2  Our method:  What’s going on:  So as we return back through the open recursive methods  We print “r”  Then we print “e”  Then we print “t” … and so on public static void printCharsReverse(String str) { if (str == null || str.length() < 1) return; else { printCharsReverse(str.substring(1)); System.out.print(str.charAt(0)); } }
  • 46.
    More Recursion page46 © Dr. Jonathan (Yahya) Cazalas Recursion: General Structure  Example using Construct 2  Our method:  What’s going on:  Will we have printed: r e t u p m o  And then we return to the original recursive method  At that point, we print a “c”, resulting in:  r e t u p m o c public static void printCharsReverse(String str) { if (str == null || str.length() < 1) return; else { printCharsReverse(str.substring(1)); System.out.print(str.charAt(0)); } }
  • 47.
    More Recursion page47 © Dr. Jonathan (Yahya) Cazalas Brief Interlude: Human Stupidity
  • 48.
    More Recursion page48 © Dr. Jonathan (Yahya) Cazalas Recursion – Practice Problem  Practice Problem:  Write a recursive method that:  Takes in two non-negative integer parameters  Returns the product of these parameters  But it does NOT use multiplication to get the answer  So if the parameters are 6 and 4  The answer would be 24  How do we do this not actually using multiplication  What another way of saying 6*4?  We are adding 6, 4 times!  6*4 = 6 + 6 + 6 + 6  So now think of your method…
  • 49.
    More Recursion page49 © Dr. Jonathan (Yahya) Cazalas Recursion – Practice Problem  Practice Problem:  Solution: // Precondition: Both parameters are // non-negative integers. // Postcondition: The product of the two // parameters is returned. public static int Multiply(int first, int second) { if (( second == 0 ) || ( first = 0 )) return 0; else return (first + Multiply(first, second-1)); }
  • 50.
    More Recursion page50 © Dr. Jonathan (Yahya) Cazalas Recursion – Towers of Hanoi  Towers of Hanoi:  Here’s the problem:  There are three vertical poles  There are 64 disks on tower 1 (left most tower)  The disks are arranged with the largest diameter disks at the bottom  Some monk has the daunting task of moving disks from one tower to another tower  Often defined as moving from Tower #1 to Tower #3  Tower #2 is just an intermediate pole  He can only move ONE disk at a time  And he MUST follow the rule of NEVER putting a bigger disk on top of a smaller disk
  • 51.
    More Recursion page51 © Dr. Jonathan (Yahya) Cazalas Recursion – Towers of Hanoi  Towers of Hanoi:  Solution:  We must find a recursive strategy  Thoughts:  Any tower with more than one disk must clearly be moved in pieces  If there is just one disk on a pole, then we move it start temp finish
  • 52.
    More Recursion page52 © Dr. Jonathan (Yahya) Cazalas Recursion – Towers of Hanoi  Towers of Hanoi:  Solution:  Irrespective of the number of disks, the following steps MUST be carried out:  The bottom disk needs to move to the destination tower 1) So step 1 must be to move all disks above the bottom disk to the intermediate tower 2) In step 2, the bottom disk can now be moved to the destination tower 3) In step 3, the disks that were initially above the bottom disk must now be put back on top  Of course, at the destination  Let’s look at the situation with only 3 disks…
  • 53.
    More Recursion page53 © Dr. Jonathan (Yahya) Cazalas Recursion – Towers of Hanoi  Towers of Hanoi:  Solution:  Step 1:  Move 2 disks from start to temp using finish Tower.  To understand the recursive routine, let us assume that we know how to solve 2 disk problem, and go for the next step.  Meaning, we “know” how to move 2 disks appropriately start temp finish start temp finish
  • 54.
    More Recursion page54 © Dr. Jonathan (Yahya) Cazalas start temp finish start temp finish Recursion – Towers of Hanoi  Towers of Hanoi:  Solution:  Step 2:  Move the (remaining) single disk from start to finish  This does not involve recursion  and can be carried out without using temp tower.  In our program, this is just a print statement  Showing what we moved and to where
  • 55.
    More Recursion page55 © Dr. Jonathan (Yahya) Cazalas start temp finish  Towers of Hanoi:  Solution:  Step 3:  Now we are at the last step of the routine.  Move the 2 disks from temp tower to finish tower using the start tower  This is also done recursively start temp finish Recursion – Towers of Hanoi
  • 56.
    More Recursion page56 © Dr. Jonathan (Yahya) Cazalas start temp finish start start temp finish 1 start temp finish 2 start temp finish 3 start temp finish 4 Recursion – Towers of Hanoi
  • 57.
    More Recursion page57 © Dr. Jonathan (Yahya) Cazalas start temp finish 6 start temp finish start temp finish 5 7 Recursion – Towers of Hanoi  # of steps needed:  We had 3 disks requiring seven steps  4 disks would require 15 steps  n disks would require 2n -1 steps  HUGE number
  • 58.
    More Recursion page58 © Dr. Jonathan (Yahya) Cazalas  Towers of Hanoi:  Solution:  Search in your book! Recursion – Towers of Hanoi
  • 59.
    More Recursion page59 © Dr. Jonathan (Yahya) Cazalas Recursion WASN’T THAT ENCHANTING!
  • 60.
    More Recursion page60 © Dr. Jonathan (Yahya) Cazalas Daily Demotivator
  • 61.
    College of Computing& Information Technology King Abdulaziz University CPCS-204 – Data Structures I More Recursion