Top Banner
1 2005 Pearson Education, Inc. All rights rese 1 5 Recursion
57

2005 Pearson Education, Inc. All rights reserved. 1 15 Recursion.

Jan 04, 2016

Download

Documents

Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: 2005 Pearson Education, Inc. All rights reserved. 1 15 Recursion.

1

2005 Pearson Education, Inc. All rights reserved.

1515

Recursion

Page 2: 2005 Pearson Education, Inc. All rights reserved. 1 15 Recursion.

2

2005 Pearson Education, Inc. All rights reserved.

It's a poor sort of memory that only works backwards.—Lewis Carroll, Alice in Wonderland

We must learn to explore all the options and possibilities that confront us in a complex and rapidly changing world. —James William Fulbright

Push on—keep moving. —Thomas Morton

O! thou hast damnable iteration, and art indeed able to corrupt a saint. —William Shakespeare

Life can only be understood backwards; but it must be lived forwards. —Soren Kierkegaard

Page 3: 2005 Pearson Education, Inc. All rights reserved. 1 15 Recursion.

3

2005 Pearson Education, Inc. All rights reserved.

OBJECTIVES

In this chapter you will learn: The concept of recursion. How to write and use recursive methods. How to determine the base case and recursion

step in a recursive algorithm. How recursive method calls are handled by

the system. The differences between recursion and

iteration, and when it is appropriate to use each.

Page 4: 2005 Pearson Education, Inc. All rights reserved. 1 15 Recursion.

4

2005 Pearson Education, Inc. All rights reserved.

15.1   Introduction

15.2   Recursion Concepts

15.3   Example Using Recursion: Factorials

15.4   Example Using Recursion: Fibonacci Series

15.5   Recursion and the Method Call Stack

15.6   Recursion vs. Iteration

15.7   String Permutations

15.8   Towers of Hanoi

15.9   Fractals

15.10   Recursive Backtracking

15.11   Wrap-Up

15.12   Internet and Web Resources

Page 5: 2005 Pearson Education, Inc. All rights reserved. 1 15 Recursion.

5

2005 Pearson Education, Inc. All rights reserved.

15.1 Introduction

• Earlier programs structured as methods that call one another in a disciplined, hierarchical manner

• Recursive methods– Call themselves

– Useful for some problems to define a method to call itself

– Can be called directly or indirectly through another method

Page 6: 2005 Pearson Education, Inc. All rights reserved. 1 15 Recursion.

6

2005 Pearson Education, Inc. All rights reserved.

Fig. 15.1 | Summary of the 32 recursion examples and exercises in this text. (Part 1 of 2)

Chapter Recursion examples and exercises in this book

15 Factorial Method (Fig. 15.3 and Fig. 15.4) Fibonacci Method (Fig. 15.5 and Fig. 15.6) String Permutations (Fig. 15.12 and Fig. 15.13) Towers of Hanoi (Fig. 15.15 and Fig. 15.16) Fractals (Fig. 15.23 and Fig. 15.24) What Does This Code Do? (Exercise 15.7, Exercise 15.12 and Exercise 15.13) Find the Error in the Following Code (Exercise 15.8) Raising an Integer to an Integer Power (Exercise 15.9) Visualizing Recursion (Exercise 15.10) Greatest Common Divisor (Exercise 15.11) Determine Whether a String Is a Palindrome (Exercise 15.14) Eight Queens (Exercise 15.15) Print an Array (Exercise 15.16) Print an Array Backward (Exercise 15.17) Minimum Value in an Array (Exercise 15.18) Star Fractal (Exercise 15.19) Maze Traversal Using Recursive Backtracking (Exercise 15.20) Generating Mazes Randomly (Exercise 15.21) Mazes of Any Size (Exercise 15.22) Time Needed to Calculate a Fibonacci Number (Exercise 15.23)

Page 7: 2005 Pearson Education, Inc. All rights reserved. 1 15 Recursion.

7

2005 Pearson Education, Inc. All rights reserved.

Fig. 15.1 | Summary of the 32 recursion examples and exercises in this text. (Part 2 of 2)

Chapter Recursion examples and exercises in this book

16 Merge Sort (Fig. 16.10 and Fig. 16.11) Linear Search (Exercise 16.8) Binary Search (Exercise 16.9) Quicksort (Exercise 16.10)

17 Binary-Tree Insert (Fig. 17.17) Preorder Traversal of a Binary Tree (Fig. 17.17) Inorder Traversal of a Binary Tree (Fig. 17.17) Postorder Traversal of a Binary Tree (Fig. 17.17) Print a Linked List Backward (Exercise 17.20) Search a Linked List (Exercise 17.21)

Page 8: 2005 Pearson Education, Inc. All rights reserved. 1 15 Recursion.

8

2005 Pearson Education, Inc. All rights reserved.

15.2 Recursion Concepts

• Recursive problem-solving elements– Base case

• Recursive method capable of solving only simplest case—the base case• If method is called with base case, method returns result

– If method is called with more complex problem, problem divided into two pieces—a piece the method knows how to do and a piece the method does not know how to do (called recursive call or recursion step)

– Recursive call/recursion step• Must resemble original problem but be slightly simpler or smaller version• Method calls fresh copy of itself to work on smaller problem• Normally includes return statement

• Indirect recursion– Recursive method calls another method that eventually makes call back

to recursive method

Page 9: 2005 Pearson Education, Inc. All rights reserved. 1 15 Recursion.

9

2005 Pearson Education, Inc. All rights reserved.

15.3 Example Using Recursion: Factorials

• Factorial of n, or n! is the productn · (n – 1) · (n – 2) · … · 1

With 1! equal to 1 and 0! Defined to be 1.

• Can be solved recursively or iteratively (nonrecursively)

• Recursive solution uses following relationship:n! = n · (n – 1)!

• Infinite recursion – recursive calls are continuously made until memory has been exhausted

– Caused by either omitting base case or writing recursion step that does not converge on base case

Page 10: 2005 Pearson Education, Inc. All rights reserved. 1 15 Recursion.

10

2005 Pearson Education, Inc. All rights reserved.

Fig. 15.2 | Recursive evaluation of 5!.

Page 11: 2005 Pearson Education, Inc. All rights reserved. 1 15 Recursion.

11

2005 Pearson Education, Inc. All rights reserved.

Outline

Factorial

Calculator.java

1 // Fig. 15.3: FactorialCalculator.java

2 // Recursive factorial method.

3

4 public class FactorialCalculator

5 {

6 // recursive method factorial

7 public long factorial( long number )

8 {

9 if ( number <= 1 ) // test for base case

10 return 1; // base cases: 0! = 1 and 1! = 1

11 else // recursion step

12 return number * factorial( number - 1 );

13 } // end method factorial

14

15 // output factorials for values 0-10

16 public void displayFactorials()

17 {

18 // calculate the factorials of 0 through 10

19 for ( int counter = 0; counter <= 10; counter++ )

20 System.out.printf( "%d! = %d\n", counter, factorial( counter ) );

21 } // end method displayFactorials

22 } // end class FactorialCalculator

Base case returns 1

Portion method knows how to do

Recursion step breaks problem into two parts: one the method knows how to do, one the method does not

Recursive call: Portion method does not know how to do; smaller version of original problem

Original call to recursive method

Page 12: 2005 Pearson Education, Inc. All rights reserved. 1 15 Recursion.

12

2005 Pearson Education, Inc. All rights reserved.

Common Programming Error 15.1

Either omitting the base case or writing the recursion step incorrectly so that it does not converge on the base case can cause a logic error known as infinite recursion, where recursive calls are continuously made until memory has been exhausted. This error is analogous to the problem of an infinite loop in an iterative (nonrecursive) solution.

Page 13: 2005 Pearson Education, Inc. All rights reserved. 1 15 Recursion.

13

2005 Pearson Education, Inc. All rights reserved.

Outline

FactorialTest.java

1 // Fig. 15.4: FactorialTest.java

2 // Testing the recursive factorial method.

3

4 public class FactorialTest

5 {

6 // calculate factorials of 0-10

7 public static void main( String args[] )

8 {

9 FactorialCalculator factorialCalculator = new FactorialCalculator();

10 factorialCalculator.displayFactorials();

11 } // end main

12 } // end class FactorialTest 0! = 1 1! = 1 2! = 2 3! = 6 4! = 24 5! = 120 6! = 720 7! = 5040 8! = 40320 9! = 362880 10! = 3628800

Calculate and display factorials

Page 14: 2005 Pearson Education, Inc. All rights reserved. 1 15 Recursion.

14

2005 Pearson Education, Inc. All rights reserved.

15.4 Example Using Recursion: Fibonacci Series

• Fibonacci series begins with 0 and 1 and has property that each subsequent Fibonacci number is the sum of previous two Fibonacci numbers.

• Series occurs in nature, ratio of successive Fibonacci numbers converges on golden ratio or golden mean

• Fibonacci series defined recursively as:fibonacci(0) = 0

fibonacci(1) = 1

fibonacci(n) = fibonacci(n – 1) + fibonacci(n – 2)

• Recursive solution for calculating Fibonacci values results in explosion of recursive method calls

Page 15: 2005 Pearson Education, Inc. All rights reserved. 1 15 Recursion.

15

2005 Pearson Education, Inc. All rights reserved.

Outline

Fibonacci

Calculator.java

1 // Fig. 15.5: FibonacciCalculator.java

2 // Recursive fibonacci method.

3

4 public class FibonacciCalculator

5 {

6 // recursive declaration of method fibonacci

7 public long fibonacci( long number )

8 {

9 if ( ( number == 0 ) || ( number == 1 ) ) // base cases

10 return number;

11 else // recursion step

12 return fibonacci( number - 1 ) + fibonacci( number - 2 );

13 } // end method fibonacci

14

15 public void displayFibonacci()

16 {

17 for ( int counter = 0; counter <= 10; counter++ )

18 System.out.printf( "Fibonacci of %d is: %d\n", counter,

19 fibonacci( counter ) );

20 } // end method displayFibonacci

21 } // end class FibonacciCalculator

Two base cases

Two recursive calls

Original call to recursive method

Page 16: 2005 Pearson Education, Inc. All rights reserved. 1 15 Recursion.

16

2005 Pearson Education, Inc. All rights reserved.

Outline

FibonacciTest.java

1 // Fig. 15.6: FibonacciTest.java

2 // Testing the recursive fibonacci method.

3

4 public class FibonacciTest

5 {

6 public static void main( String args[] )

7 {

8 FibonacciCalculator fibonacciCalculator = new FibonacciCalculator();

9 fibonacciCalculator.displayFibonacci();

10 } // end main

11 } // end class FibonacciTest Fibonacci of 0 is: 0 Fibonacci of 1 is: 1 Fibonacci of 2 is: 1 Fibonacci of 3 is: 2 Fibonacci of 4 is: 3 Fibonacci of 5 is: 5 Fibonacci of 6 is: 8 Fibonacci of 7 is: 13 Fibonacci of 8 is: 21 Fibonacci of 9 is: 34 Fibonacci of 10 is: 55

Calculate and display Fibonacci values

Page 17: 2005 Pearson Education, Inc. All rights reserved. 1 15 Recursion.

17

2005 Pearson Education, Inc. All rights reserved.

Fig. 15.7 | Set of recursive calls for fibonacci( 3 ).

Page 18: 2005 Pearson Education, Inc. All rights reserved. 1 15 Recursion.

18

2005 Pearson Education, Inc. All rights reserved.

Avoid Fibonacci-style recursive programs, because they result in an exponential “explosion” of method calls.

Performance Tip 15.1

Page 19: 2005 Pearson Education, Inc. All rights reserved. 1 15 Recursion.

19

2005 Pearson Education, Inc. All rights reserved.

15.5 Recursion and the Method Call Stack

• Method call stack used to keep track of method calls and local variables within a method call

• Just as with nonrecursive programming, recursive method calls are placed at the top of the method call stack

• As recursive method calls return, their activation records are popped off the stack and the previous recursive calls continue executing

• Current method executing is always method whose activation record is at top of stack

Page 20: 2005 Pearson Education, Inc. All rights reserved. 1 15 Recursion.

20

2005 Pearson Education, Inc. All rights reserved.

Fig. 15.8 | Method calls made within the call fibonacci( 3 ).

Page 21: 2005 Pearson Education, Inc. All rights reserved. 1 15 Recursion.

21

2005 Pearson Education, Inc. All rights reserved.

Fig. 15.9 | Method calls on the program execution stack.

Page 22: 2005 Pearson Education, Inc. All rights reserved. 1 15 Recursion.

22

2005 Pearson Education, Inc. All rights reserved.

15.6 Recursion vs. Iteration

• Any problem that can be solved recursively can be solved iteratively

• Both iteration and recursion use a control statement– Iteration uses a repetition statement

– Recursion uses a selection statement

• Iteration and recursion both involve a termination test– Iteration terminates when the loop-continuation condition fails

– Recursion terminates when a base case is reached

• Recursion can be expensive in terms of processor time and memory space, but usually provides a more intuitive solution

Page 23: 2005 Pearson Education, Inc. All rights reserved. 1 15 Recursion.

23

2005 Pearson Education, Inc. All rights reserved.

Software Engineering Observation 15.1

Any problem that can be solved recursively can also be solved iteratively (nonrecursively). A recursive approach is normally preferred over an iterative approach when the recursive approach more naturally mirrors the problem and results in a program that is easier to understand and debug. A recursive approach can often be implemented with fewer lines of code. Another reason to choose a recursive approach is that an iterative one might not be apparent.

Page 24: 2005 Pearson Education, Inc. All rights reserved. 1 15 Recursion.

24

2005 Pearson Education, Inc. All rights reserved.

Outline

Factorial

Calculator.java

1 // Fig. 15.10: FactorialCalculator.java

2 // Iterative factorial method.

3

4 public class FactorialCalculator

5 {

6 // recursive declaration of method factorial

7 public long factorial( long number )

8 {

9 long result = 1;

10

11 // iterative declaration of method factorial

12 for ( long i = number; i >= 1; i-- )

13 result *= i;

14

15 return result;

16 } // end method factorial

17

18 // output factorials for values 0-10

19 public void displayFactorials()

20 {

21 // calculate the factorials of 0 through 10

22 for ( int counter = 0; counter <= 10; counter++ )

23 System.out.printf( "%d! = %d\n", counter, factorial( counter ) );

24 } // end method displayFactorials

25 } // end class FactorialCalculator

Iterative solution uses counter-controlled repetition

Page 25: 2005 Pearson Education, Inc. All rights reserved. 1 15 Recursion.

25

2005 Pearson Education, Inc. All rights reserved.

Outline

FactorialTest.java

1 // Fig. 15.11: FactorialTest.java

2 // Testing the iterative factorial method.

3

4 public class FactorialTest

5 {

6 // calculate factorials of 0-10

7 public static void main( String args[] )

8 {

9 FactorialCalculator factorialCalculator = new FactorialCalculator();

10 factorialCalculator.displayFactorials();

11 } // end main

12 } // end class FactorialTest 0! = 1 1! = 1 2! = 2 3! = 6 4! = 24 5! = 120 6! = 720 7! = 5040 8! = 40320 9! = 362880 10! = 3628800

Page 26: 2005 Pearson Education, Inc. All rights reserved. 1 15 Recursion.

26

2005 Pearson Education, Inc. All rights reserved.

Avoid using recursion in situations requiring high performance. Recursive calls take time and consume additional memory.

Performance Tip 15.2

Page 27: 2005 Pearson Education, Inc. All rights reserved. 1 15 Recursion.

27

2005 Pearson Education, Inc. All rights reserved.

Common Programming Error 15.2

Accidentally having a nonrecursive method call itself either directly or indirectly through another method can cause infinite recursion.

Page 28: 2005 Pearson Education, Inc. All rights reserved. 1 15 Recursion.

28

2005 Pearson Education, Inc. All rights reserved.

15.7 String Permutations

• Permutations of a string of text – all the different strings that can be created by rearranging characters of original string

• Words created from permutations are known as anagrams

• Recursive solution: Remove one character, find permutations of remaining characters (recursive case), combine permutations with character that was removed

• Base case: Finding permutations for just one character – character itself is the only permutation

• Any string provides n! permutations for n characters

Page 29: 2005 Pearson Education, Inc. All rights reserved. 1 15 Recursion.

29

2005 Pearson Education, Inc. All rights reserved.

Outline

Permutation.java

(1 of 2)

1 // Fig. 15.12: Permutation.java

2 // Recursive method to find all permutations of a String.

3

4 public class Permutation

5 {

6 // recursive declaration of method permuteString

7 private void permuteString(

8 String beginningString, String endingString )

9 {

10 // base case: if string to permute is length less than or equal to

11 // 1, just display this string concatenated with beginningString

12 if ( endingString.length() <= 1 )

13 System.out.println( beginningString + endingString );

14 else // recursion step: permute endingString

15 {

16 // for each character in endingString

17 for ( int i = 0; i < endingString.length(); i++ )

18 {

19 try

20 {

21 // create new string to permute by eliminating the

22 // character at index i

23 String newString = endingString.substring( 0, i ) +

24 endingString.substring( i + 1 );

25

Base case: Combine removed characters (beginningString) with

endingString, which is only one character

Remove one character; We will find permutations for remaining characters

Page 30: 2005 Pearson Education, Inc. All rights reserved. 1 15 Recursion.

30

2005 Pearson Education, Inc. All rights reserved.

Outline

Permutation.java

(2 of 2)

26 // recursive call with a new string to permute

27 // and a beginning string to concatenate, which

28 // includes the character at index i

29 permuteString( beginningString +

30 endingString.charAt( i ), newString );

31 } // end try

32 catch ( StringIndexOutOfBoundsException exception )

33 {

34 exception.printStackTrace();

35 } // end catch

36 } // end for

37 } // end else

38 } // end method permuteString

39 } // end class Permutation

Recursive call: find permutations for remaining characters then reattach

removed characters

Page 31: 2005 Pearson Education, Inc. All rights reserved. 1 15 Recursion.

31

2005 Pearson Education, Inc. All rights reserved.

Outline

PermutationTest .java

(1 of 2)

1 // Fig. 15.13: PermutationTest.java

2 // Testing the recursive method to permute strings.

3 import java.util.Scanner;

4

5 public class PermutationTest

6 {

7 public static void main( String args[] )

8 {

9 Scanner scanner = new Scanner( System.in );

10 Permutation permutationObject = new Permutation();

11

12 System.out.print( "Enter a string: " );

13 String input = scanner.nextLine(); // retrieve String to permute

14

15 // permute String

16 permutationObject.permuteString( "", input );

17 } // end main

18 } // end class PermutationTest

Initial call to recursive method; There are no removed characters yet, so

first argument is “”

Page 32: 2005 Pearson Education, Inc. All rights reserved. 1 15 Recursion.

32

2005 Pearson Education, Inc. All rights reserved.

Outline

PermutationTest

.java

(2 of 2)

math maht mtah mtha mhat mhta amth amht atmh athm ahmt ahtm tmah tmha tamh tahm thma tham hmat hmta hamt hatm htma htam

Page 33: 2005 Pearson Education, Inc. All rights reserved. 1 15 Recursion.

33

2005 Pearson Education, Inc. All rights reserved.

15.8 Towers of Hanoi

• Classic problem – Priests in Far East are attempting to move a stack of disks from one peg to another. One disk must be moved at a time, at no time may a larger disk be placed above a smaller disk

• Recursive solution:– Move n – 1 disks from peg 1 to peg 2, using peg 3 as temporary

holding area– Move the last disk (the largest) from peg 1 to peg 3– Move the n – 1 disks from peg 2 to peg 3, using peg 1 as a

temporary holding area

• Base case: When only one disk needs to be moved – no temporary holding area needed, disk is simply moved

Page 34: 2005 Pearson Education, Inc. All rights reserved. 1 15 Recursion.

34

2005 Pearson Education, Inc. All rights reserved.

Fig. 15.14 | Towers of Hanoi for the case with four disks.

Page 35: 2005 Pearson Education, Inc. All rights reserved. 1 15 Recursion.

35

2005 Pearson Education, Inc. All rights reserved.

Outline

TowersOfHanoi.java

(1 of 2)

1 // Fig. 15.15: TowersOfHanoi.java

2 // Program solves the towers of Hanoi problem, and

3 // demonstrates recursion.

4

5 public class TowersOfHanoi

6 {

7 int numDisks; // number of disks to move

8

9 public TowersOfHanoi( int disks )

10 {

11 numDisks = disks;

12 } // end TowersOfHanoi constructor

13

14 // recusively move disks through towers

15 public void solveTowers( int disks, int sourcePeg, int destinationPeg,

16 int tempPeg )

17 {

18 // base case -- only one disk to move

19 if ( disks == 1 )

20 {

21 System.out.printf( "\n%d --> %d", sourcePeg, destinationPeg );

22 return;

23 } // end if

24

Base case: Simply display move

Page 36: 2005 Pearson Education, Inc. All rights reserved. 1 15 Recursion.

36

2005 Pearson Education, Inc. All rights reserved.

Outline

TowersOfHanoi.java

(2 of 2)

25 // recursion step -- move disk to tempPeg, then to destinationPeg

26 // move ( disks - 1 ) disks from sourcePeg to tempPeg recursively

27 solveTowers( disks - 1, sourcePeg, tempPeg, destinationPeg );

28

29 // move last disk from sourcePeg to destinationPeg

30 System.out.printf( "\n%d --> %d", sourcePeg, destinationPeg );

31

32 // move ( disks - 1 ) disks from tempPeg to destinationPeg

33 solveTowers( disks - 1, tempPeg, destinationPeg, sourcePeg );

34 } // end method solveTowers

35 } // end class TowersOfHanoi

Move n-1 disks from peg 1 to peg 2

Move last disk from peg 1 to peg 3

Move n-1 disks from peg 2 to peg 3Use peg 1 as temporary holding area

Use peg 3 as temporary holding area

Page 37: 2005 Pearson Education, Inc. All rights reserved. 1 15 Recursion.

37

2005 Pearson Education, Inc. All rights reserved.

Outline

TowersOfHanoiTest

.java

1 // Fig. 15.16: TowersOfHanoiTest.java

2 // Test the solution to the Towers of Hanoi problem.

3

4 public class TowersOfHanoiTest

5 {

6 public static void main( String args[] )

7 {

8 int startPeg = 1; // value 1 used to indicate startPeg in output

9 int endPeg = 3; // value 3 used to indicate endPeg in output

10 int tempPeg = 2; // value 2 used to indicate tempPeg in output

11 int totalDisks = 3; // number of disks

12 TowersOfHanoi towersOfHanoi = new TowersOfHanoi( totalDisks );

13

14 // initial nonrecursive call: move all disks.

15 towersOfHanoi.solveTowers( totalDisks, startPeg, endPeg, tempPeg );

16 } // end main

17 } // end class TowersOfHanoiTest 1 --> 3 1 --> 2 3 --> 2 1 --> 3 2 --> 1 2 --> 3 1 --> 3

Make initial call to recursive method

Page 38: 2005 Pearson Education, Inc. All rights reserved. 1 15 Recursion.

38

2005 Pearson Education, Inc. All rights reserved.

15.9 Fractals

• Fractal – a geometric figure that often can be generated from a pattern repeated recursively an infinite number of times

• Pattern applied to each segment of original figure

• Benoit Mandelbrot introduced term “fractal,” along with specifics of how fractals are created and their practical applications

– Help us better understand patterns in nature, the human body and the universe

– Popular art form

Page 39: 2005 Pearson Education, Inc. All rights reserved. 1 15 Recursion.

39

2005 Pearson Education, Inc. All rights reserved.

15.9 Fractals

• Self-similar property – fractals have this property in the case that, when subdivided into parts, each resembles a reduced-size copy of the whole

• If part is exact copy of original, fractal is said to be strictly self similar

• Each time pattern is applied, fractal is said to be at new level or depth

• Fractal examples: Koch Curve, Koch Snowflake

Page 40: 2005 Pearson Education, Inc. All rights reserved. 1 15 Recursion.

40

2005 Pearson Education, Inc. All rights reserved.

Fig. 15.17 | Koch Curve fractal.

(a) (b)

(c) (d)

(e) (f)

Page 41: 2005 Pearson Education, Inc. All rights reserved. 1 15 Recursion.

41

2005 Pearson Education, Inc. All rights reserved.

Fig. 15.18’ | “Lo fractal” at level 0.

Page 42: 2005 Pearson Education, Inc. All rights reserved. 1 15 Recursion.

42

2005 Pearson Education, Inc. All rights reserved.

Fig. 15.19 | Determining points C and D for level 1 of “Lo fractal.”

Page 43: 2005 Pearson Education, Inc. All rights reserved. 1 15 Recursion.

43

2005 Pearson Education, Inc. All rights reserved.

Fig. 15.20 | “Lo fractal” at level 1, with C and D points determined for level 2. [Note: The fractal at level 0 is included as a dashed line as a reminder of where the line was located in relation to the

current fractal.]

Page 44: 2005 Pearson Education, Inc. All rights reserved. 1 15 Recursion.

44

2005 Pearson Education, Inc. All rights reserved.

Fig. 15.21 | “Lo fractal” at level 2, with dashed lines from level 1 provided.

Page 45: 2005 Pearson Education, Inc. All rights reserved. 1 15 Recursion.

45

2005 Pearson Education, Inc. All rights reserved.

Fig. 15.22 | “Lo fractal” at level 2.

Page 46: 2005 Pearson Education, Inc. All rights reserved. 1 15 Recursion.

46

2005 Pearson Education, Inc. All rights reserved.

Outline

Fractal.java

(1 of 5)

1 // Fig. 15.23: Fractal.java

2 // Demonstrates user interface for drawing a fractal.

3 import java.awt.Color;

4 import java.awt.FlowLayout;

5 import java.awt.event.ActionEvent;

6 import java.awt.event.ActionListener;

7 import javax.swing.JFrame;

8 import javax.swing.JButton;

9 import javax.swing.JLabel;

10 import javax.swing.JPanel;

11 import javax.swing.JColorChooser;

12

13 public class Fractal extends JFrame

14 {

15 private final int WIDTH = 400; // define width of GUI

16 private final int HEIGHT = 480; // define height of GUI

17 private final int MIN_LEVEL = 0;

18 private Color color = Color.BLUE;

19

20 private JButton changeColorJButton, increaseLevelJButton,

21 decreaseLevelJButton;

22 private JLabel levelJLabel;

23 private FractalJPanel drawSpace;

24 private JPanel mainJPanel, controlJPanel;

25

26 // set up GUI

27 public Fractal()

28 {

29 super( "Fractal" );

30

Page 47: 2005 Pearson Education, Inc. All rights reserved. 1 15 Recursion.

47

2005 Pearson Education, Inc. All rights reserved.

Outline

Fractal.java

(2 of 5)

31 // set up control panel

32 controlJPanel = new JPanel();

33 controlJPanel.setLayout( new FlowLayout() );

34

35 // set up color button and register listener

36 changeColorJButton = new JButton( "Color" );

37 controlJPanel.add( changeColorJButton );

38 changeColorJButton.addActionListener(

39 new ActionListener() // anonymous inner class

40 {

41 // process changeColorJButton event

42 public void actionPerformed( ActionEvent event )

43 {

44 color = JColorChooser.showDialog(

45 Fractal.this, "Choose a color", color );

46

47 // set default color, if no color is returned

48 if ( color == null )

49 color = Color.BLUE;

50

51 drawSpace.setColor( color );

52 } // end method actionPerformed

53 } // end anonymous inner class

54 ); // end addActionListener

55

Page 48: 2005 Pearson Education, Inc. All rights reserved. 1 15 Recursion.

48

2005 Pearson Education, Inc. All rights reserved.

Outline

Fractal.java

(3 of 5)

56 // set up decrease level button to add to control panel and

57 // register listener

58 decreaseLevelJButton = new JButton( "Decrease Level" );

59 controlJPanel.add( decreaseLevelJButton );

60 decreaseLevelJButton.addActionListener(

61 new ActionListener() // anonymous inner class

62 {

63 // process decreaseLevelJButton event

64 public void actionPerformed( ActionEvent event )

65 {

66 int level = drawSpace.getLevel();

67 level--; // decrease level by one

68

69 // modify level if possible

70 if ( level >= MIN_LEVEL )

71 {

72 levelJLabel.setText( "Level: " + level );

73 drawSpace.setLevel( level );

74 repaint();

75 } // end if

76 } // end method actionPerformed

77 } // end anonymous inner class

78 ); // end addActionListener

79

Retrieve current levelDecrease level

Set new level

Redraw fractal up to new level

Page 49: 2005 Pearson Education, Inc. All rights reserved. 1 15 Recursion.

49

2005 Pearson Education, Inc. All rights reserved.

Outline

Fractal.java

(4 of 5)

80 // set up increase level button to add to control panel

81 // and register listener

82 increaseLevelJButton = new JButton( "Increase Level" );

83 controlJPanel.add( increaseLevelJButton );

84 increaseLevelJButton.addActionListener(

85 new ActionListener() // anonymous inner class

86 {

87 // process increaseLevelJButton event

88 public void actionPerformed( ActionEvent event )

89 {

90 int level = drawSpace.getLevel();

91 level++; // increase level by one

92

93 // modify level if possible

94 if ( level >= MIN_LEVEL )

95 {

96 levelJLabel.setText( "Level: " + level );

97 drawSpace.setLevel( level );

98 repaint();

99 } // end if

100 } // end method actionPerformed

101 } // end anonymous inner class

102 ); // end addActionListener

103

104 // set up levelJLabel to add to controlJPanel

105 levelJLabel = new JLabel( "Level: 0" );

106 controlJPanel.add( levelJLabel );

107

Retrieve current levelIncrease level

Set new level

Redraw fractal up to new level

Page 50: 2005 Pearson Education, Inc. All rights reserved. 1 15 Recursion.

50

2005 Pearson Education, Inc. All rights reserved.

Outline

Fractal.java

(5 of 5)

108 drawSpace = new FractalJPanel( 0 );

109

110 // create mainJPanel to contain controlJPanel and drawSpace

111 mainJPanel = new JPanel();

112 mainJPanel.add( controlJPanel );

113 mainJPanel.add( drawSpace );

114

115 add( mainJPanel ); // add JPanel to JFrame

116

117 setSize( WIDTH, HEIGHT ); // set size of JFrame

118 setVisible( true ); // display JFrame

119 } // end Fractal constructor

120

121 public static void main( String args[] )

122 {

123 Fractal demo = new Fractal();

124 demo.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );

125 } // end main

126 } // end class Fractal

Page 51: 2005 Pearson Education, Inc. All rights reserved. 1 15 Recursion.

51

2005 Pearson Education, Inc. All rights reserved.

Outline

FractalJPanel.java

(1 of 6)

1 // Fig. 15.24: FractalJPanel.java

2 // FractalJPanel demonstrates recursive drawing of a fractal.

3 import java.awt.Graphics;

4 import java.awt.Color;

5 import java.awt.Dimension;

6 import javax.swing.JPanel;

7

8 public class FractalJPanel extends JPanel

9 {

10 private Color color; // stores color used to draw fractal

11 private int level; // stores current level of fractal

12

13 private final int WIDTH = 400; // defines width of JPanel

14 private final int HEIGHT = 400; // defines height of JPanel

15

16 // set the initial fractal level to the value specified

17 // and set up JPanel specifications

18 public FractalJPanel( int currentLevel )

19 {

20 color = Color.BLUE; // initialize drawing color to blue

21 level = currentLevel; // set initial fractal level

22 setBackground( Color.WHITE );

23 setPreferredSize( new Dimension( WIDTH, HEIGHT ) );

24 } // end FractalJPanel constructor

25

Page 52: 2005 Pearson Education, Inc. All rights reserved. 1 15 Recursion.

52

2005 Pearson Education, Inc. All rights reserved.

Outline

FractalJPanel.java

(2 of 6)

26 // draw fractal recursively

27 public void drawFractal( int level, int xA, int yA, int xB,

28 int yB, Graphics g )

29 {

30 // base case: draw a line connecting two given points

31 if ( level == 0 )

32 g.drawLine( xA, yA, xB, yB );

33 else // recursion step: determine new points, draw next level

34 {

35 // calculate midpoint between (xA, yA) and (xB, yB)

36 int xC = ( xA + xB ) / 2;

37 int yC = ( yA + yB ) / 2;

38

39 // calculate the fourth point (xD, yD) which forms an

40 // isosceles right triangle between (xA, yA) and (xC, yC)

41 // where the right angle is at (xD, yD)

42 int xD = xA + ( xC - xA ) / 2 - ( yC - yA ) / 2;

43 int yD = yA + ( yC - yA ) / 2 + ( xC - xA ) / 2;

44

45 // recursively draw the Fractal

46 drawFractal( level - 1, xD, yD, xA, yA, g );

47 drawFractal( level - 1, xD, yD, xC, yC, g );

48 drawFractal( level - 1, xD, yD, xB, yB, g );

49 } // end else

50 } // end method drawFractal

51

Coordinates of first point for line where fractal is being appliedCoordinates of second point for line

where fractal is being appliedBase case: Simply draw line, pattern is

not applied

Recursion step: Apply fractal patternCalculate midpoint

Calculate point to form right triangle

Apply pattern to three new lines

Page 53: 2005 Pearson Education, Inc. All rights reserved. 1 15 Recursion.

53

2005 Pearson Education, Inc. All rights reserved.

Outline

FractalJPanel.java

(3 of 6)

52 // start the drawing of fractal

53 public void paintComponent( Graphics g )

54 {

55 super.paintComponent( g );

56

57 // draw fractal pattern

58 g.setColor( color );

59 drawFractal( level, 100, 90, 290, 200, g );

60 } // end method paintComponent

61

62 // set the drawing color to c

63 public void setColor( Color c )

64 {

65 color = c;

66 } // end method setColor

67

68 // set the new level of recursion

69 public void setLevel( int currentLevel )

70 {

71 level = currentLevel;

72 } // end method setLevel

73

Make first call to recursive method whenever window is repainted

Page 54: 2005 Pearson Education, Inc. All rights reserved. 1 15 Recursion.

54

2005 Pearson Education, Inc. All rights reserved.

Outline

FractalJPanel.java

(4 of 6)

74 // returns level of recursion

75 public int getLevel()

76 {

77 return level;

78 } // end method getLevel

79 } // end class FractalJPanel

Page 55: 2005 Pearson Education, Inc. All rights reserved. 1 15 Recursion.

55

2005 Pearson Education, Inc. All rights reserved.

Outline

FractalJPanel.java

(5 of 6)

Page 56: 2005 Pearson Education, Inc. All rights reserved. 1 15 Recursion.

56

2005 Pearson Education, Inc. All rights reserved.

Outline

FractalJPanel.java

(6 of 6)

Page 57: 2005 Pearson Education, Inc. All rights reserved. 1 15 Recursion.

57

2005 Pearson Education, Inc. All rights reserved.

15.10 Recursive Backtracking

• Recursive Backtracking – process of using recursion to return to earlier decision point

• If one set of recursive calls does not result in solution, program backs up to previous decision point and makes different decision, often resulting in another set of recursive calls

• Examples– Maze problem

– Eight-Queens problem