1992-2007 pearson education, inc. all rights reserved. 1 15 recursion

52
1 1992-2007 Pearson Education, Inc. All rights rese 1 5 Recursion

Upload: stanley-simmons

Post on 30-Dec-2015

227 views

Category:

Documents


4 download

TRANSCRIPT

1

1992-2007 Pearson Education, Inc. All rights reserved.

1515

Recursion

2

1992-2007 Pearson Education, Inc. All rights reserved.

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

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

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

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

Push on—keep moving. —Thomas Morton

3

1992-2007 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. What geometric shapes called fractals are and how to

draw them using recursion. What recursive backtracking is and why it is an

effective problem-solving technique.

4

1992-2007 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   Towers of Hanoi

15.8   Fractals

15.9   Recursive Backtracking

15.10   Wrap-Up

15.11   Internet and Web Resources

5

1992-2007 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

6

1992-2007 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) Towers of Hanoi (Fig. 15.13 and Fig. 15.14) Fractals (Fig. 15.21 and Fig. 15.22) 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)

7

1992-2007 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)

8

1992-2007 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

9

1992-2007 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

10

1992-2007 Pearson Education, Inc. All rights reserved.

Fig. 15.2 | Recursive evaluation of 5!.

11

1992-2007 Pearson Education, Inc. All rights reserved.

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

12

1992-2007 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.

13

1992-2007 Pearson Education, Inc. All rights reserved.

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

14

1992-2007 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

15

1992-2007 Pearson Education, Inc. All rights reserved.

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

16

1992-2007 Pearson Education, Inc. All rights reserved.

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

17

1992-2007 Pearson Education, Inc. All rights reserved.

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

18

1992-2007 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

19

1992-2007 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

20

1992-2007 Pearson Education, Inc. All rights reserved.

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

21

1992-2007 Pearson Education, Inc. All rights reserved.

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

22

1992-2007 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

23

1992-2007 Pearson Education, Inc. All rights reserved.

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

24

1992-2007 Pearson Education, Inc. All rights reserved.

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

25

1992-2007 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.

26

1992-2007 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

27

1992-2007 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.

28

1992-2007 Pearson Education, Inc. All rights reserved.

15.7 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

29

1992-2007 Pearson Education, Inc. All rights reserved.

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

30

1992-2007 Pearson Education, Inc. All rights reserved.

1 // Fig. 15.13: 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

31

1992-2007 Pearson Education, Inc. All rights reserved.

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

32

1992-2007 Pearson Education, Inc. All rights reserved.

1 // Fig. 15.14: 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

33

1992-2007 Pearson Education, Inc. All rights reserved.

15.8 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

34

1992-2007 Pearson Education, Inc. All rights reserved.

15.8 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

35

1992-2007 Pearson Education, Inc. All rights reserved.

Fig. 15.15 | Koch Curve fractal.

(a) (b)

(c) (d)

(e) (f)

36

1992-2007 Pearson Education, Inc. All rights reserved.

Fig. 15.16 | “Lo fractal” at level 0.

37

1992-2007 Pearson Education, Inc. All rights reserved.

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

38

1992-2007 Pearson Education, Inc. All rights reserved.

Fig. 15.18 | “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.]

39

1992-2007 Pearson Education, Inc. All rights reserved.

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

40

1992-2007 Pearson Education, Inc. All rights reserved.

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

41

1992-2007 Pearson Education, Inc. All rights reserved.

1 // Fig. 15.21: 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

42

1992-2007 Pearson Education, Inc. All rights reserved.

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

43

1992-2007 Pearson Education, Inc. All rights reserved.

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

44

1992-2007 Pearson Education, Inc. All rights reserved.

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

45

1992-2007 Pearson Education, Inc. All rights reserved.

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

46

1992-2007 Pearson Education, Inc. All rights reserved.

1 // Fig. 15.22: 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

47

1992-2007 Pearson Education, Inc. All rights reserved.

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

48

1992-2007 Pearson Education, Inc. All rights reserved.

52 // start drawing the 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

49

1992-2007 Pearson Education, Inc. All rights reserved.

74 // returns level of recursion

75 public int getLevel()

76 {

77 return level;

78 } // end method getLevel

79 } // end class FractalJPanel

50

1992-2007 Pearson Education, Inc. All rights reserved.

51

1992-2007 Pearson Education, Inc. All rights reserved.

52

1992-2007 Pearson Education, Inc. All rights reserved.

15.9 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