+ All Categories
Home > Documents > 1Recursion Recursion is a fundamental programming technique that can provide an elegant solution...

1Recursion Recursion is a fundamental programming technique that can provide an elegant solution...

Date post: 03-Jan-2016
Category:
Upload: dwight-watts
View: 212 times
Download: 0 times
Share this document with a friend
83
1 Recursion Recursion Recursion is a fundamental programming Recursion is a fundamental programming technique that can provide an elegant technique that can provide an elegant solution certain kinds of problems solution certain kinds of problems We will focus on: We will focus on: thinking in a recursive manner thinking in a recursive manner programming in a recursive manner programming in a recursive manner the correct use of recursion the correct use of recursion recursion examples recursion examples
Transcript
Page 1: 1Recursion  Recursion is a fundamental programming technique that can provide an elegant solution certain kinds of problems  We will focus on: thinking.

1

RecursionRecursion

Recursion is a fundamental programming technique Recursion is a fundamental programming technique that can provide an elegant solution certain kinds of that can provide an elegant solution certain kinds of problemsproblems

We will focus on:We will focus on:• thinking in a recursive mannerthinking in a recursive manner• programming in a recursive mannerprogramming in a recursive manner• the correct use of recursionthe correct use of recursion• recursion examplesrecursion examples

Page 2: 1Recursion  Recursion is a fundamental programming technique that can provide an elegant solution certain kinds of problems  We will focus on: thinking.

2

Recursive ThinkingRecursive Thinking

A A recursive definitionrecursive definition is one which uses the word or is one which uses the word or concept being defined in the definition itself, e.g.concept being defined in the definition itself, e.g.

“ “A friend is a person who is a friend “A friend is a person who is a friend “

When defining an English word, a When defining an English word, a recursive definitionrecursive definition is not effective.is not effective.

But in other situations, a recursive definition can be the But in other situations, a recursive definition can be the best way to express a conceptbest way to express a concept

Page 3: 1Recursion  Recursion is a fundamental programming technique that can provide an elegant solution certain kinds of problems  We will focus on: thinking.

3

Recursive ThinkingRecursive Thinking

We have We have used methods that call other methods to used methods that call other methods to help help them solve a problem. them solve a problem.

Sometimes Sometimes methodsmethods need need to call to call themselves themselves again. again.

Page 4: 1Recursion  Recursion is a fundamental programming technique that can provide an elegant solution certain kinds of problems  We will focus on: thinking.

A Simple Recursive MethodA Simple Recursive Method

4

1.1. // This method does not stop - it is in an infinite loop// This method does not stop - it is in an infinite loop2.2. public static void forgetMeNot()public static void forgetMeNot()

3.3. { {

4.4. System.out.println(“I Miss You”); System.out.println(“I Miss You”);

5.5. forgetMeNot();forgetMeNot(); // a recursive call to itself again// a recursive call to itself again

6.6. }}  

The method prints “I Miss You” and then calls itself infinitely:The method prints “I Miss You” and then calls itself infinitely:  

– I Miss YouI Miss You– I Miss YouI Miss You– I Miss YouI Miss You– ……( forever!)( forever!)

Page 5: 1Recursion  Recursion is a fundamental programming technique that can provide an elegant solution certain kinds of problems  We will focus on: thinking.

Writing a recursive methodWriting a recursive method

Problem Statement:Problem Statement: The previous method does not stop executing so there is The previous method does not stop executing so there is

an endless loop:an endless loop:

Problem: Write a recursive method that: Problem: Write a recursive method that:

prints “I Miss You” prints “I Miss You” nn times and times and

signs off “Love , Me”.signs off “Love , Me”.

It will run n timesIt will run n times

5

Page 6: 1Recursion  Recursion is a fundamental programming technique that can provide an elegant solution certain kinds of problems  We will focus on: thinking.

public class GreetingCardpublic class GreetingCard1.1.{ {

2.2.// main method calls forgetMeNot with parameter “3”// main method calls forgetMeNot with parameter “3”

3.3. public static void main(String[] args)public static void main(String[] args)4.4. {{

5.5. forgetMeNot(3); forgetMeNot(3); // invokes method for the first time// invokes method for the first time

6.6. System.out.println(“Love, Me”); System.out.println(“Love, Me”); ((SPOT 1SPOT 1))

7.7. } }

8.8.//***************************************************//***************************************************

9.9. public static void public static void forgetMeNot(int n) forgetMeNot(int n)

//// nn is the number of times the message is printed.is the number of times the message is printed.b { { b if (n != 0) if (n != 0) // base case which stop recursive calls// base case which stop recursive callsb { {

b System.out.println(“System.out.println(“I Miss YouI Miss You”); ”); b forgetMeNot(n – 1 ); forgetMeNot(n – 1 ); // the recursive callthe recursive callb ((SPOT 2SPOT 2) // There could be more code here) // There could be more code hereb }}b }} 6

Page 7: 1Recursion  Recursion is a fundamental programming technique that can provide an elegant solution certain kinds of problems  We will focus on: thinking.

Writing Recursive methodsWriting Recursive methods

OutputOutput

I Miss YouI Miss YouI Miss YouI Miss YouI Miss YouI Miss YouLove, MeLove, Me

   The recursive method forgetMeNot(...) The recursive method forgetMeNot(...)

is called by main(...) and passed the argument “3”. is called by main(...) and passed the argument “3”.

7

Page 8: 1Recursion  Recursion is a fundamental programming technique that can provide an elegant solution certain kinds of problems  We will focus on: thinking.

Main method begins with the call Main method begins with the call forgetMeNot(3)forgetMeNot(3)::

What the method doesWhat the method does:: prints “I Miss you” prints “I Miss you” Calls forgetMeNot(2):Calls forgetMeNot(2): prints “I Miss You” prints “I Miss You” Calls forgetMeNot(1): Calls forgetMeNot(1): prints “I Miss You” prints “I Miss You” Calls forgetMeNot(0):Calls forgetMeNot(0):

**** next does nothing because the condition (n!=0) evaluates to false -it is 0 **** next does nothing because the condition (n!=0) evaluates to false -it is 0 forgetMeNot(0) then forgetMeNot(0) then returns to the previous call of:returns to the previous call of:

forgetMeNot(1), forgetMeNot(1), picks up at location where it left (picks up at location where it left (SPOT 2SPOT 2))

forgetMeNot(1)forgetMeNot(1) has no more code after recursive call in ( has no more code after recursive call in (SPOT 2SPOT 2)) •

Program control returns to the suspended Program control returns to the suspended

forgetMeNot(2) forgetMeNot(2) - no more code at ( - no more code at (SPOT 2SPOT 2))

concontrol returns to forgetMeNot(3):trol returns to forgetMeNot(3):

Last method done so passes control back to mainLast method done so passes control back to main

Main: prints “Love, Me” at Main: prints “Love, Me” at ((SPOT 1SPOT 1)) 8

Page 9: 1Recursion  Recursion is a fundamental programming technique that can provide an elegant solution certain kinds of problems  We will focus on: thinking.

Visualization of method callVisualization of method callss

9

1.1. main main

2.2. forgetMeNot(3)forgetMeNot(3)

3.3. “I Miss You”“I Miss You”

4.4. forgetMeNot(2)forgetMeNot(2)

5.5. “I Miss You”“I Miss You”

6.6. forgetMeNot(1)forgetMeNot(1)

7.7. “I Miss You”“I Miss You”

8.8. forgetMeNot(0) forgetMeNot(0) -- base case-- base case

9.9. returnreturn

10.10. Return to (1) Return to (1) // to where it left the method// to where it left the method

11.11. Return to (2)Return to (2)

12.12. Return to (3)Return to (3)

13.13. “Love, Me”“Love, Me”

The trace is read from top to bottom as the program executes: The trace is read from top to bottom as the program executes:

Indentations are made every time a recursive call is made. Indentations are made every time a recursive call is made.

When a method When a method returns to where it left the calling method (AT SPOT 2)returns to where it left the calling method (AT SPOT 2)

the indentation goes back to the previous level. the indentation goes back to the previous level.

Execution continues at the statement following the recursive call. (Execution continues at the statement following the recursive call. (SPOT 1)SPOT 1)

  

Page 10: 1Recursion  Recursion is a fundamental programming technique that can provide an elegant solution certain kinds of problems  We will focus on: thinking.

10

Recursive ProgrammingRecursive Programming

Just because we can Just because we can use recursion to solve a problem, use recursion to solve a problem,

that does that does not meannot mean this is the this is the optimal solution.optimal solution.

The The iterative version is easier to understand and iterative version is easier to understand and requires less memory if N is a large number. requires less memory if N is a large number.

For instance why not just print out For instance why not just print out forgetMeNot three forgetMeNot three times in a loop??????times in a loop??????

Page 11: 1Recursion  Recursion is a fundamental programming technique that can provide an elegant solution certain kinds of problems  We will focus on: thinking.

11

Infinite RecursionInfinite Recursion

All recursive definitions have to have a All recursive definitions have to have a non-recursive part non-recursive part - a stopping case or base case - a stopping case or base case

If they didn't, there would be If they didn't, there would be no way to terminate the no way to terminate the recursive pathrecursive path

Such a definition would cause Such a definition would cause infinite recursioninfinite recursion

This problem is similar to an This problem is similar to an infinite loopinfinite loop

Page 12: 1Recursion  Recursion is a fundamental programming technique that can provide an elegant solution certain kinds of problems  We will focus on: thinking.

12

RecursionRecursion

The non-recursive part is often called the The non-recursive part is often called the base case. base case.

e.ge.g if (n != 0) if (n != 0) // base case which stop recursive calls// base case which stop recursive calls

The algorithm must ensure that the The algorithm must ensure that the base case is reachedbase case is reached..

Page 13: 1Recursion  Recursion is a fundamental programming technique that can provide an elegant solution certain kinds of problems  We will focus on: thinking.

Solving a Recursive ProblemSolving a Recursive Problem

Recursion is based on a key problem-Recursion is based on a key problem-

divide and conquer and self-similarity.divide and conquer and self-similarity.

Repeatedly breaking down a big problem Repeatedly breaking down a big problem

into a sequence of smaller and smaller problems into a sequence of smaller and smaller problems

until we arrive at the base case.until we arrive at the base case.

13

Page 14: 1Recursion  Recursion is a fundamental programming technique that can provide an elegant solution certain kinds of problems  We will focus on: thinking.

14

RecursionRecursion

Look at the task of printing the characters of Look at the task of printing the characters of “hello“hello””

It involves printing the It involves printing the first character first character and then the and then the method calls itself with the method calls itself with the first character removed. first character removed.

Solving this task involves the similar task of printing Solving this task involves the similar task of printing hello hello minus the first character (look up subString minus the first character (look up subString method in the String classmethod in the String class

Page 15: 1Recursion  Recursion is a fundamental programming technique that can provide an elegant solution certain kinds of problems  We will focus on: thinking.

15

RecursionRecursion

/* /* prints each character of prints each character of S ( S ( str = “hello”str = “hello”))

1.1. public void public void printString(String str) printString(String str) 2.2. {{

3.3. if( str.length() == 0 ) if( str.length() == 0 ) // base case// base case

4.4. return return // leave the method// leave the method5.5. elseelse

6.6. {{

7.7. System.out.print( str.charAt(0) ); //System.out.print( str.charAt(0) ); //print first charprint first char8.8. printString(str.substring(1printString(str.substring(1));// REMOVES ONE CHAR));// REMOVES ONE CHAR

9.9. } // end of method} // end of method

str.substring(1)str.substring(1) returns the string returns the string starting at “e”starting at “e”

For each subsequent call it For each subsequent call it removes the first character removes the first character

Page 16: 1Recursion  Recursion is a fundamental programming technique that can provide an elegant solution certain kinds of problems  We will focus on: thinking.

HELLO – PRINTING CHARACTERSHELLO – PRINTING CHARACTERS

FOR INPUT OF ‘HELLO’FOR INPUT OF ‘HELLO’

OUTPUT: value stored -str = “HELLO”OUTPUT: value stored -str = “HELLO” HH hello hello E elloE ello

L lloL llo

L L lo lo 00 O O

16

Page 17: 1Recursion  Recursion is a fundamental programming technique that can provide an elegant solution certain kinds of problems  We will focus on: thinking.

17

Recursive DefinitionsRecursive Definitions

For any positive integer, For any positive integer, N is defined to be the product of all integers between 1 N is defined to be the product of all integers between 1

and N inclusiveand N inclusive

This definition can be expressed recursively as:This definition can be expressed recursively as:

1! = 11! = 1

N! = N * (N-1)!N! = N * (N-1)!

The factorial is defined in terms of another factorialThe factorial is defined in terms of another factorial

Eventually, the base case of 1! is reachedEventually, the base case of 1! is reached

Page 18: 1Recursion  Recursion is a fundamental programming technique that can provide an elegant solution certain kinds of problems  We will focus on: thinking.

18

Recursive DefinitionsRecursive Definitions

5!5! 5!5!

5 * 4!5 * 4!

4 * 3!4 * 3!

3 * 2!3 * 2!

2 * 1!2 * 1!

11

1 = BASE CASE1 = BASE CASE

2

6

24

120

Page 19: 1Recursion  Recursion is a fundamental programming technique that can provide an elegant solution certain kinds of problems  We will focus on: thinking.

How recursion worksHow recursion works

The code of a recursive method must be structured to The code of a recursive method must be structured to handle both the:handle both the:

base case which will end the recursive calls and base case which will end the recursive calls and

the recursive casethe recursive case

19

Page 20: 1Recursion  Recursion is a fundamental programming technique that can provide an elegant solution certain kinds of problems  We will focus on: thinking.

20

ExampleExample

To write a method that stacks non-negative numbers to the To write a method that stacks non-negative numbers to the screen vertically such as 1 2 3 4 :screen vertically such as 1 2 3 4 :

11

22

33

44

We might break the problem into two parts: We might break the problem into two parts:

1.1. Print all the digits Print all the digits but the last one but the last one stacked vertically stacked vertically

2. Print the last one.2. Print the last one.

Page 21: 1Recursion  Recursion is a fundamental programming technique that can provide an elegant solution certain kinds of problems  We will focus on: thinking.

21

An exampleAn example To print the actual number we would To print the actual number we would

1.1. divide the number by 10 to get the first three digits anddivide the number by 10 to get the first three digits and

2.2. use the mod operator to get the last digit. use the mod operator to get the last digit.

The pseudocode is:The pseudocode is:

if the number has only one digit if the number has only one digit // base case// base case

{{

write that digit to outputwrite that digit to output

}}

else {else {

Write the digits Write the digits of number/10 of number/10 verticallyvertically

write the write the single digit of number % 10 - last digitsingle digit of number % 10 - last digit }}

Page 22: 1Recursion  Recursion is a fundamental programming technique that can provide an elegant solution certain kinds of problems  We will focus on: thinking.

22

The WriteVertical methodThe WriteVertical method1.1. public static void writeVertical(int number) public static void writeVertical(int number)

{{

1.1. if (number < 10) if (number < 10) // base case// base case2.2. System.out.println(number); System.out.println(number); // prints number under 10.

3. else

4.4. { {

5.5. // divides number by 10 and calls itself again// divides number by 10 and calls itself again6.6. writeVertical(number/10); writeVertical(number/10); // // call itself again (no /10).call itself again (no /10).

7.7.

8.8. // prints the last digit WHEN RECURSION UNWINDS// prints the last digit WHEN RECURSION UNWINDS

9.9. System.out.println(number % 10); System.out.println(number % 10); 10.10. }}

11.11. }}

Page 23: 1Recursion  Recursion is a fundamental programming technique that can provide an elegant solution certain kinds of problems  We will focus on: thinking.

23

writeVerticalwriteVertical The The base case is base case is : :

when the number when the number has only 1 digit. has only 1 digit.

And then that digit is printed. And then that digit is printed.

e.g. number = 4 (e.g. number = 4 (4 % 10 = 4 4 % 10 = 4 ))

The The recursive call recursive call occurs where:occurs where:

// // writeVertical calls itself until it reaches the base case writeVertical calls itself until it reaches the base case – –

number < 10 number < 10 // base case// base case

// digits are printed in unwinding phase// digits are printed in unwinding phase System.out.println(number % 10); System.out.println(number % 10);

Page 24: 1Recursion  Recursion is a fundamental programming technique that can provide an elegant solution certain kinds of problems  We will focus on: thinking.

24

public static void writeVertical(int number) public static void writeVertical(int number) {{

1.1. public static void writeVertical(int number) public static void writeVertical(int number) {{

1.1. if (number < 10) if (number < 10) // base case// base case2. System.out.println(number); System.out.println(number); // prints numbers under // prints numbers under

1010.

3. else

{{

55.. writeVertical(writeVertical(number/10number/10)); ; // call itself until base // call itself until base case case

// Spot 1 // Spot 1 – – location to return to when recursion location to return to when recursion unwindsunwinds

66. . System.out.println( System.out.println( number % 10 number % 10 ));; } } }}

Page 25: 1Recursion  Recursion is a fundamental programming technique that can provide an elegant solution certain kinds of problems  We will focus on: thinking.

25

TRACING EXECUTIONTRACING EXECUTION((

TRACING EXECUTIONTRACING EXECUTION

Activation Record for first call to Activation Record for first call to superWriteVerticalsuperWriteVertical

number: 36number: 36

When the method returns, the When the method returns, the computation should begin at computation should begin at line SPOT1(line 5) line SPOT1(line 5) of of

the programthe program..

Activation Record Activation Record - second - second call call to superWriteVerticalto superWriteVertical

number: 3number: 3

Prints out the number Prints out the number 33

(number is less than (number is less than 10)10)

When the method returns, the When the method returns, the computation should begin at computation should begin at SPOT 1 SPOT 1 of the program.of the program.

Activation Record Activation Record – – returns to previous call to returns to previous call to superWriteVertical when number is 36superWriteVertical when number is 36

The computation should begin at The computation should begin at SPOT 1 SPOT 1 of the program of the program where it prints the 6where it prints the 6

Page 26: 1Recursion  Recursion is a fundamental programming technique that can provide an elegant solution certain kinds of problems  We will focus on: thinking.

How the Activation calls workHow the Activation calls work

When the recursive call to superWritevertical (36) make a When the recursive call to superWritevertical (36) make a call to to superWritevertical ( 3)call to to superWritevertical ( 3)

The number “3” is printed out. The number “3” is printed out.

The Activation Record for the call is popped from the The Activation Record for the call is popped from the stack and stack and

Activation Record tells the computer where to re-start Activation Record tells the computer where to re-start execution – execution –

» at SPOT 1.at SPOT 1.

26

Page 27: 1Recursion  Recursion is a fundamental programming technique that can provide an elegant solution certain kinds of problems  We will focus on: thinking.

27

Tracing ExecutionTracing ExecutionThe record is:The record is:

superWriteVertical(36) superWriteVertical(36) makes a recursive call to:makes a recursive call to:

superWriteVertical(3)superWriteVertical(3) which prints out the “3” which prints out the “3”

There is no more code so execution There is no more code so execution

returns to returns to spot1spot1

// The last line after Spot1 writes out // The last line after Spot1 writes out digit 6digit 6

System.out.println( System.out.println( 36 % 10 36 % 10 )); ;

Page 28: 1Recursion  Recursion is a fundamental programming technique that can provide an elegant solution certain kinds of problems  We will focus on: thinking.

28

RecursionRecursion If another method - called If another method - called method 2method 2 - is called from within - is called from within

method 1, method 1,

method 1’s execution is temporarily stopped and the method 1’s execution is temporarily stopped and the same same information is stored for method 2.information is stored for method 2.

It stores It stores the location of the call for the second method the location of the call for the second method ..

It will continue to this for every recursive method call.It will continue to this for every recursive method call.

This information is stored in Activation RecordsThis information is stored in Activation Records

Page 29: 1Recursion  Recursion is a fundamental programming technique that can provide an elegant solution certain kinds of problems  We will focus on: thinking.

29

Using RecursionUsing Recursion

Consider the task of repeatedly displaying a set of Consider the task of repeatedly displaying a set of images in a mosaic that is reminiscent of looking in images in a mosaic that is reminiscent of looking in two mirrors reflecting each other.two mirrors reflecting each other.

The The base case is reached when the area for the base case is reached when the area for the images shrinks to a certain size.images shrinks to a certain size.

See See MirroredPictures.java

Page 30: 1Recursion  Recursion is a fundamental programming technique that can provide an elegant solution certain kinds of problems  We will focus on: thinking.

30

RecursionRecursion The entire area is divided into The entire area is divided into 4 quadrants, 4 quadrants, separated by separated by

lines. lines.

A picture of the world(with a circle indicating the A picture of the world(with a circle indicating the Himalayan mountain section) Himalayan mountain section) is in the top-right quadrant. is in the top-right quadrant.

a picture of Mt. Everest a picture of Mt. Everest - The bottom-left quadrant contain- The bottom-left quadrant contain

a picture of a mountain goata picture of a mountain goat - in - in the bottom-right quadrant the bottom-right quadrant

Page 31: 1Recursion  Recursion is a fundamental programming technique that can provide an elegant solution certain kinds of problems  We will focus on: thinking.

31

Tiled PicturesTiled Pictures

Page 32: 1Recursion  Recursion is a fundamental programming technique that can provide an elegant solution certain kinds of problems  We will focus on: thinking.

32

Repeating PicturesRepeating Pictures

In the top left quadrant contains a copy of the In the top left quadrant contains a copy of the entire collage, including itself. entire collage, including itself.

In this smaller version you can see the three In this smaller version you can see the three simple pictures in their three quadrants. simple pictures in their three quadrants.

And again, in the upper-left corner the picture And again, in the upper-left corner the picture is repeated (including itself). is repeated (including itself).

..

Page 33: 1Recursion  Recursion is a fundamental programming technique that can provide an elegant solution certain kinds of problems  We will focus on: thinking.

33

Mirrored_ImagesMirrored_Images This effect is created easily using recursion. This effect is created easily using recursion.

In the applet, the paint method invokes another method called In the applet, the paint method invokes another method called draw pictures(). draw pictures().

The draw_pictures() method accepts a parameter that defines The draw_pictures() method accepts a parameter that defines the the size of the area in which pictures are displayed. size of the area in which pictures are displayed.

It draws the It draws the three standard images using drawImage(). three standard images using drawImage().

The draw_pictures method draws the upper left quadrant The draw_pictures method draws the upper left quadrant recursively. recursively.

Page 34: 1Recursion  Recursion is a fundamental programming technique that can provide an elegant solution certain kinds of problems  We will focus on: thinking.

34

public class TiledPictures extends JAppletpublic class TiledPictures extends JApplet{{ private final int APPLET_WIDTH = 320; private final int APPLET_WIDTH = 320; private final int APPLET_HEIGHT = 320; private final int APPLET_HEIGHT = 320; private final int MIN = 20; // smallest picture size private final int MIN = 20; // smallest picture size

private Image world, everest, goat; private Image world, everest, goat;//-----------------------------------------------------------------//----------------------------------------------------------------- // Loads the images. // Loads the images. //----------------------------------------------------------------- //----------------------------------------------------------------- public void init() public void init() { { world = getImage (getDocumentBase(), "world.gif"); world = getImage (getDocumentBase(), "world.gif"); everest = getImage (getDocumentBase(), "everest.gif"); everest = getImage (getDocumentBase(), "everest.gif"); goat = getImage (getDocumentBase(), "goat.gif"); goat = getImage (getDocumentBase(), "goat.gif");

setSize (APPLET_WIDTH, APPLET_HEIGHT); setSize (APPLET_WIDTH, APPLET_HEIGHT); } }

Page 35: 1Recursion  Recursion is a fundamental programming technique that can provide an elegant solution certain kinds of problems  We will focus on: thinking.

35

//-----------------------------------------------------------------//----------------------------------------------------------------- //Performs the initial call to the drawPictures method. //Performs the initial call to the drawPictures method. //----------------------------------------------------------------- //----------------------------------------------------------------- public void paint (Graphics page) public void paint (Graphics page) { { drawPictures (APPLET_WIDTH, page); drawPictures (APPLET_WIDTH, page); } }}}

// Starts with the full size of the applet which will // be // Starts with the full size of the applet which will // be divided for every subsequent calldivided for every subsequent call

Page 36: 1Recursion  Recursion is a fundamental programming technique that can provide an elegant solution certain kinds of problems  We will focus on: thinking.

36

//-----------------------------------------------------------------//-----------------------------------------------------------------// // Draws the three images, then calls itself recursively.Draws the three images, then calls itself recursively.// reducing the size of the images with each call.// reducing the size of the images with each call. //-----------------------------------------------------------------//----------------------------------------------------------------- public void drawPictures (int size, Graphics pagpublic void drawPictures (int size, Graphics page)e) { { page.drawLine (size/2, 0, size/2, size); page.drawLine (size/2, 0, size/2, size); // vertical// vertical page.drawLine (0, size/2, size, size/2); page.drawLine (0, size/2, size, size/2); // horizontal// horizontal

page.drawImage (everest, 0, size/2, size/2, size/2, this);page.drawImage (everest, 0, size/2, size/2, size/2, this); page.drawImage (goat, size/2, 0, size/2, size/2, this); page.drawImage (goat, size/2, 0, size/2, size/2, this); page.drawImage (world, size/2, size/2, size/2, size/2, this);page.drawImage (world, size/2, size/2, size/2, size/2, this);

if if (size > MIN) (size > MIN) // if there is room to draw, call again// if there is room to draw, call again drawPictures (size/2, page); drawPictures (size/2, page); }}

Page 37: 1Recursion  Recursion is a fundamental programming technique that can provide an elegant solution certain kinds of problems  We will focus on: thinking.

37

Mirrored_ImagesMirrored_Images

On each invocation, On each invocation,

if the if the drawing area is large enough

the draw_pictures method is invoked again, using a the draw_pictures method is invoked again, using a smaller drawing area. smaller drawing area.

Eventually the Eventually the drawing area becomes so small that the drawing area becomes so small that the recursive call is not performed.recursive call is not performed.

Page 38: 1Recursion  Recursion is a fundamental programming technique that can provide an elegant solution certain kinds of problems  We will focus on: thinking.

Halving the size of the pictureHalving the size of the picture

Each time the draw-pictures method is invoked, Each time the draw-pictures method is invoked,

the size passed as a parameter is used to determine the the size passed as a parameter is used to determine the area in which the pictures are presented area in which the pictures are presented

relative to the co-ordinates <0,0>relative to the co-ordinates <0,0>

38

Page 39: 1Recursion  Recursion is a fundamental programming technique that can provide an elegant solution certain kinds of problems  We will focus on: thinking.

39

Drawing MirrorsDrawing Mirrors The drawImage method automatically scales the pictures The drawImage method automatically scales the pictures

to fit in the area indicated. to fit in the area indicated.

The The base case base case of the recursion in this problem of the recursion in this problem specifies a specifies a minimum size for the drawing area. minimum size for the drawing area.

Because Because the size is the size is decreased each tidecreased each time, me,

eventually the base case is reached eventually the base case is reached and the recursion and the recursion stops. stops.

That is why the last upper left That is why the last upper left corner is empty in the corner is empty in the smallest version of the collage.smallest version of the collage.

Page 40: 1Recursion  Recursion is a fundamental programming technique that can provide an elegant solution certain kinds of problems  We will focus on: thinking.

40

Maze TraversalMaze Traversal

We can use recursion to find a path through a mazeWe can use recursion to find a path through a maze

From each location, From each location, we can search in each directiowe can search in each directionn

Recursion keeps track of the path through the mazeRecursion keeps track of the path through the maze

The The base case base case is an is an invalid move invalid move or or reaching the final reaching the final destinationdestination

See See MazeSearch.java See See Maze.java

Page 41: 1Recursion  Recursion is a fundamental programming technique that can provide an elegant solution certain kinds of problems  We will focus on: thinking.

41

Using RecursionUsing Recursion

A maze is solved by trial and error –A maze is solved by trial and error –

choosing a direction,choosing a direction,

following a pathfollowing a path, ,

returning to a returning to a previous point previous point if the wrong move is made.if the wrong move is made.

As such, it is another good candidate for a recursive As such, it is another good candidate for a recursive solution. solution.

Page 42: 1Recursion  Recursion is a fundamental programming technique that can provide an elegant solution certain kinds of problems  We will focus on: thinking.

In In Maze_Search.java, Maze_Search.java,

a 2-D a 2-D array of integers filled with 0’s and 1’s. array of integers filled with 0’s and 1’s.

A A ‘1’ indicates a clear path and ‘1’ indicates a clear path and

a a ‘0’ a blocked path.‘0’ a blocked path. As the maze is solved As the maze is solved these parameters are changedthese parameters are changed to other values to other values (3,1) (3,1) toto

indicate indicate attempted and successful attempted and successful paths through the paths through the maze.maze.

42

Page 43: 1Recursion  Recursion is a fundamental programming technique that can provide an elegant solution certain kinds of problems  We will focus on: thinking.

43

// // Class Maze represents a maze of characters. The goal is to Class Maze represents a maze of characters. The goal is to getget// from the top left corner to the bottom right, following a path// from the top left corner to the bottom right, following a path// of 1's.// of 1's.

class Maze {class Maze {  

int[][] grid = {{1,1,1,0,1,1,0,0,0,1,1,1,1},int[][] grid = {{1,1,1,0,1,1,0,0,0,1,1,1,1}, {1,0,1,1,1,0,1,1,1,1,0,0,1},{1,0,1,1,1,0,1,1,1,1,0,0,1}, {0,0,0,0,1,0,1,0,1,0,1,0,0},{0,0,0,0,1,0,1,0,1,0,1,0,0}, {1,1,1,0,1,1,1,0,1,0,1,1,1},{1,1,1,0,1,1,1,0,1,0,1,1,1}, {1,0,1,0,0,0,0,1,1,1,0,0,1},{1,0,1,0,0,0,0,1,1,1,0,0,1}, {1,0,1,1,1,1,1,1,0,1,1,1,1},{1,0,1,1,1,1,1,1,0,1,1,1,1}, {1,0,0,0,0,0,0,0,0,0,0,0,0},{1,0,0,0,0,0,0,0,0,0,0,0,0}, {1,1,1,1,1,1,1,1,1,1,1,1,1}{1,1,1,1,1,1,1,1,1,1,1,1,1}};};

Page 44: 1Recursion  Recursion is a fundamental programming technique that can provide an elegant solution certain kinds of problems  We will focus on: thinking.

44

Recursion - MazeRecursion - Maze

The only valid moves are The only valid moves are right, left, up and down right, left, up and down

with with no diagonal movesno diagonal moves allowed. allowed.

The goal The goal is to start in the is to start in the upper-left corner upper-left corner of the maze of the maze (0,0) and find a path that reaches the (0,0) and find a path that reaches the

bottom-right corner. bottom-right corner.

Page 45: 1Recursion  Recursion is a fundamental programming technique that can provide an elegant solution certain kinds of problems  We will focus on: thinking.

Maze_SearchMaze_Search class class

The The Maze_SearchMaze_Search class class contain the main method which contain the main method which instantiates the maze and prints out it as a matrix.instantiates the maze and prints out it as a matrix.

It solves the maze if possible and It solves the maze if possible and

prints out the solved version of the maze.prints out the solved version of the maze.

45

Page 46: 1Recursion  Recursion is a fundamental programming technique that can provide an elegant solution certain kinds of problems  We will focus on: thinking.

Traverse – determines valid movesTraverse – determines valid moves

The recursive method The recursive method traversetraverse () ()returns a returns a boolean value boolean value that indicates whether a solution was found. that indicates whether a solution was found.

First the method determines if a move to that row and First the method determines if a move to that row and column is column is valid.valid.

A move is considered valid if:A move is considered valid if:

11. It stays within the grid. It stays within the grid

2. if the grid contains a ‘1’ in that cell2. if the grid contains a ‘1’ in that cell

46

Page 47: 1Recursion  Recursion is a fundamental programming technique that can provide an elegant solution certain kinds of problems  We will focus on: thinking.

47

RecursionRecursion The initial call to The initial call to traversetraverse passes in the upper-left passes in the upper-left

location(0,0). location(0,0).

If the move is valid, If the move is valid,

the the grid entry is changed from a 1 to a 3grid entry is changed from a 1 to a 3

marking this location marking this location as visitedas visited

so that later we so that later we don’t retrace don’t retrace out steps. out steps.

Page 48: 1Recursion  Recursion is a fundamental programming technique that can provide an elegant solution certain kinds of problems  We will focus on: thinking.

48

//======================================//====================================== // // Determines if a specific location is valid.Determines if a specific location is valid. //=//===================================================================================== private boolean valid (int row, int column) {private boolean valid (int row, int column) {   boolean result = false;boolean result = false; // check if cell is in the bounds of the matrix if (row >= 0 && row < grid.length &&if (row >= 0 && row < grid.length && column >= 0 && column < grid[0].length)column >= 0 && column < grid[0].length)  

// check if cell is not blocked and not // check if cell is not blocked and not previously triedpreviously tried if (grid[row][column] == 1)if (grid[row][column] == 1) result = true;result = true;   return result;return result;

} // method valid} // method valid

Page 49: 1Recursion  Recursion is a fundamental programming technique that can provide an elegant solution certain kinds of problems  We will focus on: thinking.

49

Then the Then the traverse method traverse method determines if the maze has determines if the maze has been completed -- been completed --

by having reached the by having reached the bottom right location of the maze. bottom right location of the maze.

The 3 possibilities for the base case for each recursive The 3 possibilities for the base case for each recursive call are:call are:

11. an invalid move because it is out of bounds . an invalid move because it is out of bounds

2. an invalid move because it has been tried before 2. an invalid move because it has been tried before (it (it contains a 3) contains a 3) so we go back to a previous cellso we go back to a previous cell

3. a move that arrives at the final location – 3. a move that arrives at the final location – Success!Success!

Page 50: 1Recursion  Recursion is a fundamental programming technique that can provide an elegant solution certain kinds of problems  We will focus on: thinking.

50

// Recursively traverse the maze. and inserts special characters indicating locations // Recursively traverse the maze. and inserts special characters indicating locations that have beenthat have been tried and that eventually become part of the solution.tried and that eventually become part of the solution.

public boolean traverse (int row, int column) {public boolean traverse (int row, int column) {    boolean done = false;boolean done = false; if (valid (row, column)) if (valid (row, column)) // calls method to determine the cell holds a 1// calls method to determine the cell holds a 1 {{   grid[row][column] = 3grid[row][column] = 3; ; // marks cell as tried and sets it to 3// marks cell as tried and sets it to 3    if (row == grid.length-1 && column == grid[0].length-1)if (row == grid.length-1 && column == grid[0].length-1) done = true; done = true; // maze is solved ,we have reached the end// maze is solved ,we have reached the end elseelse {{ done = traverse (row+1, column); done = traverse (row+1, column); // move down as far as possible// move down as far as possible if (!done) if (!done) // if that did not work, // if that did not work, done = traverse (row, column+1); done = traverse (row, column+1); // move right// move right if (!done) if (!done) // if that did not work, // if that did not work, done = traverse (row-1, column); done = traverse (row-1, column); // move up// move up if (!done) if (!done) // if that did not work, // if that did not work, done = traverse (row, column-1); done = traverse (row, column-1); // move left// move left }} if (done) if (done) // part of the final path - this is marked when the calls unwind// part of the final path - this is marked when the calls unwind grid[row][column] = 7; grid[row][column] = 7; // this marks the path to the final solution// this marks the path to the final solution } // closes if valid} // closes if valid return done; return done; } // method traverse} // method traverse

Page 51: 1Recursion  Recursion is a fundamental programming technique that can provide an elegant solution certain kinds of problems  We will focus on: thinking.

51

MazesMazes

If the current location is not the If the current location is not the bottom-right bottom-right corner corner which is where the we want to go to,which is where the we want to go to,

we search for a solution in each of the primary we search for a solution in each of the primary directions . directions . Down, Right ,Up and LeftDown, Right ,Up and Left

First, First, we look down by recursively calling the we look down by recursively calling the traverse method and passing in the new location traverse method and passing in the new location

The logic of the solve methods starts all over again The logic of the solve methods starts all over again using this new position. using this new position.

Page 52: 1Recursion  Recursion is a fundamental programming technique that can provide an elegant solution certain kinds of problems  We will focus on: thinking.

52

MazesMazes A solution is found by either A solution is found by either starting down starting down from the from the

current location or it is not found. current location or it is not found.

If it’s not found, we try If it’s not found, we try

moving right, then up. moving right, then up.

Finally if no direction yields a correct path Finally if no direction yields a correct path

we try left. we try left.

If no direction from this location yields a correct solution,If no direction from this location yields a correct solution,

then then there is no path from this location and the traverse there is no path from this location and the traverse method returns false.method returns false.

Page 53: 1Recursion  Recursion is a fundamental programming technique that can provide an elegant solution certain kinds of problems  We will focus on: thinking.

53

Maze_SearchMaze_Search

If a solution was found from the current location, If a solution was found from the current location,

the grid entry is changed to a 7. the grid entry is changed to a 7.

These are marked when the method calls unwind. These are marked when the method calls unwind.

Page 54: 1Recursion  Recursion is a fundamental programming technique that can provide an elegant solution certain kinds of problems  We will focus on: thinking.

SOLUTIONSOLUTION

Therefore, when the final maze is printed:Therefore, when the final maze is printed:

The locations left on the stack are part of the solution.The locations left on the stack are part of the solution.

1.1. the the zeroszeros still indicate a blocked path and still indicate a blocked path and

2.2.A A 1 1 indicates an open path that was never triedindicates an open path that was never tried

3.3.A A 3 3 indicates a path that was tried but failed to yield a indicates a path that was tried but failed to yield a correct solutioncorrect solution

4.4. A A 7 7 indicates a indicates a part of the final solution part of the final solution of the mazeof the maze

54

Page 55: 1Recursion  Recursion is a fundamental programming technique that can provide an elegant solution certain kinds of problems  We will focus on: thinking.

55

Maze_SearchMaze_Search Maze_Search Solution moves are down right up and leftMaze_Search Solution moves are down right up and left

  The The yellow marks a false path yellow marks a false path – that is we could not – that is we could not move in any direction when backtracking - look at the move in any direction when backtracking - look at the path of 3’spath of 3’s

7777770110001111011000111130307777770077777710011001000000007700770077003300007777770077777700770033333377007700000000777733000033770077777777777700333333337700000000000000000000000077777777777777777777777777

Page 56: 1Recursion  Recursion is a fundamental programming technique that can provide an elegant solution certain kinds of problems  We will focus on: thinking.

56

FractalsFractals Fractals are very complex pictures generated by a Fractals are very complex pictures generated by a

computer from a single formula. computer from a single formula.

Very often they are very colorful and look beautiful. Very often they are very colorful and look beautiful.

A fractal gets created by using iterations. A fractal gets created by using iterations.

This means that one formula is repeated with slightly This means that one formula is repeated with slightly different values over and over againdifferent values over and over again, ,

taking into account the results from the previoustaking into account the results from the previous iteration. iteration.

Page 57: 1Recursion  Recursion is a fundamental programming technique that can provide an elegant solution certain kinds of problems  We will focus on: thinking.

57

FractalsFractals

The results are then graphed. The results are then graphed.

In fractals, In fractals, the little parts of them look like the the little parts of them look like the big picturebig picture, , and and

when one zooms in closer, when one zooms in closer,

one will find more and moreone will find more and more

repeating copies of the original. repeating copies of the original.

Page 58: 1Recursion  Recursion is a fundamental programming technique that can provide an elegant solution certain kinds of problems  We will focus on: thinking.

58

FractalsFractals

A A fractalfractal is a geometric shape made up of the same is a geometric shape made up of the same pattern pattern

repeated in different sizes and orientationsrepeated in different sizes and orientations

The The Koch SnowflakeKoch Snowflake is a particular fractal that begins is a particular fractal that begins with an with an equilateral triangleequilateral triangle

To get a higher order of the fractal, the sides of the To get a higher order of the fractal, the sides of the triangle are replaced with angled line segmentstriangle are replaced with angled line segments

Page 59: 1Recursion  Recursion is a fundamental programming technique that can provide an elegant solution certain kinds of problems  We will focus on: thinking.

FractalsFractals

59

Fractals are used in graphics to Fractals are used in graphics to

artificially produce natural scenes such as mountains, artificially produce natural scenes such as mountains, clouds trees and others objects.clouds trees and others objects.

Basically, Basically, a line segment is raised in the middla line segment is raised in the middle e and and moved vertically a random moved vertically a random distance. distance.

The The end points remain in the same place. end points remain in the same place.

Page 60: 1Recursion  Recursion is a fundamental programming technique that can provide an elegant solution certain kinds of problems  We will focus on: thinking.

60

FractalsFractals The order below is The order below is order 2order 2

( the line is broken into two segments).( the line is broken into two segments).

Now, we have two smaller segments of the same line.Now, we have two smaller segments of the same line.

Page 61: 1Recursion  Recursion is a fundamental programming technique that can provide an elegant solution certain kinds of problems  We will focus on: thinking.

61

FractalsFractals

By repetitively By repetitively grabbing the midpoint grabbing the midpoint of each line segment of each line segment and and

moving it up or down some random distance, moving it up or down some random distance,

the line becomes ever more the line becomes ever more jagged.jagged.

After many steps a After many steps a ragged line ragged line is created that is created that

approximates a approximates a picture of an island or a cloud picture of an island or a cloud or theor the

tops of mountains.tops of mountains.

..

Page 62: 1Recursion  Recursion is a fundamental programming technique that can provide an elegant solution certain kinds of problems  We will focus on: thinking.

Fracta;sFracta;s

If we If we magnified any given segment magnified any given segment of the line, of the line,

it would look like a it would look like a small portion of the whole small portion of the whole lineline. .

62

Page 63: 1Recursion  Recursion is a fundamental programming technique that can provide an elegant solution certain kinds of problems  We will focus on: thinking.

63

FractalsFractals To create a method, we must input the

two locations of the endpoints of the original line.

Distances are measured from the top side and left side of the drawing area.

E.g. coordinates for x = 100, y = 55

Distances are measured Distances are measured from the top side and left from the top side and left side of the drawing areaside of the drawing areaHorizontalHorizontal

distancedistance

100,55100,55

Page 64: 1Recursion  Recursion is a fundamental programming technique that can provide an elegant solution certain kinds of problems  We will focus on: thinking.

64

Method randomFractalMethod randomFractal

public static void public static void randomFractal( int leftx, int leftYrandomFractal( int leftx, int leftY)){ { int int rightx;rightx; int int rightY;rightY; Graphics drawArea Graphics drawArea;// instance variables;// instance variables

if if (rightX - leftX <= STOP) (rightX - leftX <= STOP) // area too small to draw – base case// area too small to draw – base case

drawArea.drawLine(leftX, leftY,rightX, rightY);drawArea.drawLine(leftX, leftY,rightX, rightY);

else else {{ midX = (leftX + rightX) \2; // midX = (leftX + rightX) \2; // divide x in halfdivide x in half

midY = (leftY + rightY) \2midY = (leftY + rightY) \2; ; // divide y in half// divide y in half

Page 65: 1Recursion  Recursion is a fundamental programming technique that can provide an elegant solution certain kinds of problems  We will focus on: thinking.

(con’d)(con’d)

// calculate degree of variation in line size – delta// calculate degree of variation in line size – delta

deltadelta = (int) (Math.random() - 0.5) * (rightX - leftX); = (int) (Math.random() - 0.5) * (rightX - leftX);

midY += delta; // add random value to ymidY += delta; // add random value to y

// two recursive calls to the left and right sides// two recursive calls to the left and right sides

randomFractal(leftX, leftY,midX, midY, drawArearandomFractal(leftX, leftY,midX, midY, drawArea););

randomFractal(midX, midY,rightX, rightY, drawArea);randomFractal(midX, midY,rightX, rightY, drawArea);

} // close method} // close method

65

Page 66: 1Recursion  Recursion is a fundamental programming technique that can provide an elegant solution certain kinds of problems  We will focus on: thinking.

66

Fractals- ANALYSIS OF LINEFractals- ANALYSIS OF LINE

leftX, leftX, leftYleftY(70, 60)(70, 60)

rightX, rightYrightX, rightY (270, 35)(270, 35)

midX and midYmidX and midY = = The midpoint of the lineThe midpoint of the line. . ( (170 & 47170 & 47) )

midX = (leftX + rightX) /2midX = (leftX + rightX) /2

The The y-midpointy-midpoint must be must be shifted up or downshifted up or down a a random random amount amount – –

this shift IS this shift IS NO MORE than half the distance from leftX and leftNO MORE than half the distance from leftX and leftYY. .

The The result result is stored in is stored in deltadelta::

delta = (int) (Math.random() - 0.5) * (rightX - leftX);

midX,midYmidX,midY(170, 47)(170, 47)

Page 67: 1Recursion  Recursion is a fundamental programming technique that can provide an elegant solution certain kinds of problems  We will focus on: thinking.

67

FractalsFractals The call to random produces a number from The call to random produces a number from

--0.5 to 0.5. 0.5 to 0.5.

The result is rounded to an integer.The result is rounded to an integer.

Then the result is added to Then the result is added to midYmidY::

midY += delta.midY += delta.

Now we have two segments:Now we have two segments:

1. From the 1. From the left end point of the original segmentleft end point of the original segment to the to the displaced midpoint.displaced midpoint.

2. From 2. From the midpoint to the right endpoint.the midpoint to the right endpoint.

Page 68: 1Recursion  Recursion is a fundamental programming technique that can provide an elegant solution certain kinds of problems  We will focus on: thinking.

FractalsFractals

To create a random fractal for each of these segments, To create a random fractal for each of these segments,

we use two recursive calls.we use two recursive calls.

randomFractal(leftX, leftY, midX, midY, drawArea);randomFractal(leftX, leftY, midX, midY, drawArea);

randomFractal(midX, midY,rightX, rightY, drawArea);randomFractal(midX, midY,rightX, rightY, drawArea);

Each recursive call changes the co-ordinates of the lineEach recursive call changes the co-ordinates of the line

68

Page 69: 1Recursion  Recursion is a fundamental programming technique that can provide an elegant solution certain kinds of problems  We will focus on: thinking.

69

FractalsFractals

randomFractal(leftX, leftY, midX, midY, drawArea);randomFractal(leftX, leftY, midX, midY, drawArea);

randomFractal(midX, midY,rightX, rightY, drawArea);randomFractal(midX, midY,rightX, rightY, drawArea);

The first two arguments of the first recursive call are the The first two arguments of the first recursive call are the left endpoints left endpoints of the original segment of the original segment

and the and the right coordinates right coordinates of the of the leftmost segment leftmost segment or the or the midpoint of the original segment.midpoint of the original segment.

The second recursive call handles the The second recursive call handles the right segment right segment of of the original line.the original line.

Page 70: 1Recursion  Recursion is a fundamental programming technique that can provide an elegant solution certain kinds of problems  We will focus on: thinking.

70

FractalsFractals

Now, we have to find a Now, we have to find a stopping case.stopping case.

The stopping case should be when theThe stopping case should be when the

leftX and rightX get too close. leftX and rightX get too close.

At this point we draw a line:At this point we draw a line:

if(rightX - leftX <= STOP)if(rightX - leftX <= STOP) drawArea.drawLine(leftX, leftY,rightX, rightY);drawArea.drawLine(leftX, leftY,rightX, rightY);

Page 71: 1Recursion  Recursion is a fundamental programming technique that can provide an elegant solution certain kinds of problems  We will focus on: thinking.

7171

Koch SnowflakesKoch Snowflakes

BecomesBecomes

Page 72: 1Recursion  Recursion is a fundamental programming technique that can provide an elegant solution certain kinds of problems  We will focus on: thinking.

72

Koch SnowflakesKoch Snowflakes

Page 73: 1Recursion  Recursion is a fundamental programming technique that can provide an elegant solution certain kinds of problems  We will focus on: thinking.

73

Koch SnowflakesKoch Snowflakes

Page 74: 1Recursion  Recursion is a fundamental programming technique that can provide an elegant solution certain kinds of problems  We will focus on: thinking.

74

Towers of HanoiTowers of Hanoi

The The Towers of HanoiTowers of Hanoi is a puzzle made up ofis a puzzle made up of

1. 1. three vertical pegs and three vertical pegs and

2. several disks that slide on the pegs2. several disks that slide on the pegs

The disks are of varying size, initially placed on one peg The disks are of varying size, initially placed on one peg

The largest disk IS on the bottom with increasingly The largest disk IS on the bottom with increasingly smaller ones on topsmaller ones on top

Page 75: 1Recursion  Recursion is a fundamental programming technique that can provide an elegant solution certain kinds of problems  We will focus on: thinking.

TOWERS OF HANOITOWERS OF HANOI

The goal is to move all of the disks from one peg The goal is to move all of the disks from one peg to another under the following rules:to another under the following rules:

• We can move We can move only one disk at a timeonly one disk at a time

• We We cannot move a larger disk on top of a cannot move a larger disk on top of a smaller onesmaller one

75

Page 76: 1Recursion  Recursion is a fundamental programming technique that can provide an elegant solution certain kinds of problems  We will focus on: thinking.

76

Towers of HanoiTowers of Hanoi

An iterative solution to the Towers of Hanoi is quite An iterative solution to the Towers of Hanoi is quite complexcomplex

A recursive solution is much shorter and more elegantA recursive solution is much shorter and more elegant

See See SolveTowers.java See See TowersOfHanoi.java

Read Chapter 4.3 in your text for a very Read Chapter 4.3 in your text for a very good explanation of the Towers OF HANOIgood explanation of the Towers OF HANOI

Page 77: 1Recursion  Recursion is a fundamental programming technique that can provide an elegant solution certain kinds of problems  We will focus on: thinking.

77

Tower Of HanoiTower Of Hanoi

Goal: Move all disks from A to CGoal: Move all disks from A to C

Rule:Rule:• No bigger disk is on top of smaller disk at any No bigger disk is on top of smaller disk at any

timetime• Move one disk at a timeMove one disk at a time

A B C

4 disks

Page 78: 1Recursion  Recursion is a fundamental programming technique that can provide an elegant solution certain kinds of problems  We will focus on: thinking.

78

Recursive Code For Hanoi TowerRecursive Code For Hanoi Tower

N = number of disksN = number of disks

void move(int n, char start, char finish, char buf)void move(int n, char start, char finish, char buf)

{{

if(n==1)if(n==1)

System.out.println(“Move from”+start+“ to”+finish);System.out.println(“Move from”+start+“ to”+finish);

elseelse

{{

move(n-1,start,buf,finish);move(n-1,start,buf,finish);

System.out.println(“Move from”+start+ “ to”+finish);System.out.println(“Move from”+start+ “ to”+finish);

move(n-1, buf, finish, start);move(n-1, buf, finish, start);

}}

}}

Page 79: 1Recursion  Recursion is a fundamental programming technique that can provide an elegant solution certain kinds of problems  We will focus on: thinking.

79

4-disk Example4-disk Example

A B C

Page 80: 1Recursion  Recursion is a fundamental programming technique that can provide an elegant solution certain kinds of problems  We will focus on: thinking.

80

4-disk Example4-disk Example

A B C

Page 81: 1Recursion  Recursion is a fundamental programming technique that can provide an elegant solution certain kinds of problems  We will focus on: thinking.

81

4-disk Example4-disk Example

A B C

Page 82: 1Recursion  Recursion is a fundamental programming technique that can provide an elegant solution certain kinds of problems  We will focus on: thinking.

82

Demo Of HanoiDemo Of Hanoi

A nice animation of Hanoi online:A nice animation of Hanoi online:• http://www.mazeworks.com/hanoi/index.htm

Page 83: 1Recursion  Recursion is a fundamental programming technique that can provide an elegant solution certain kinds of problems  We will focus on: thinking.

83

Don't look downDon't look down

When you write or debug a recursive function, When you write or debug a recursive function, think about think about thisthis level level onlyonly

Wherever there is a recursive call, Wherever there is a recursive call, assume that it works correctlyassume that it works correctly

If you can get If you can get thisthis level correct, level correct,

you will automatically get you will automatically get allall levels corre levels correctct

You really can't understand more than one level at a time, You really can't understand more than one level at a time,

so don’t even tryso don’t even try


Recommended