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

Slides:



Advertisements
Similar presentations
© 2006 Pearson Education Chapter 8: Recursion Presentation slides for Java Software Solutions for AP* Computer Science A 2nd Edition by John Lewis, William.
Advertisements

© 2010 Pearson Addison-Wesley. All rights reserved. Addison Wesley is an imprint of CHAPTER 7: Recursion Java Software Structures: Designing and Using.
Chapter 8: Recursion Java Software Solutions
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Recursive methods. Recursion A recursive method is a method that contains a call to itself Often used as an alternative to iteration when iteration is.
© Janice Regan, CMPT 102, Sept CMPT 102 Introduction to Scientific Computer Programming Recursion.
Slides prepared by Rose Williams, Binghamton University Chapter 11 Recursion.
1 Recursion  Recursion is a fundamental programming technique that can provide an elegant solution certain kinds of problems  Chapter 11 of the book.
Chapter Day 25. © 2007 Pearson Addison-Wesley. All rights reserved Agenda Day 25 Problem set 5 Posted (Last one)  Due Dec 8 Friday Capstones Schedule.
Recursion. Objectives At the conclusion of this lesson, students should be able to Explain what recursion is Design and write functions that use recursion.
Recursion … just in case you didn’t love loops enough …
Chapter 10 Recursion. Copyright © 2005 Pearson Addison-Wesley. All rights reserved Chapter Objectives Explain the underlying concepts of recursion.
Chapter 11 Recursion Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Chapter Day 25. © 2007 Pearson Addison-Wesley. All rights reserved Agenda Day 25 Problem set 5 Posted (Last one)  Due Dec 8 Capstones Schedule  3rd.
Copyright © 2003 Pearson Education, Inc. Slide 1.
ELC 310 Day 24. © 2004 Pearson Addison-Wesley. All rights reserved11-2 Agenda Questions? Problem set 5 Parts A Corrected  Good results Problem set 5.
CHAPTER 10 Recursion. 2 Recursive Thinking Recursion is a programming technique in which a method can call itself to solve a problem A recursive definition.
Chapter 11 Recursion. © 2004 Pearson Addison-Wesley. All rights reserved11-2 Recursion Recursion is a fundamental programming technique that can provide.
© 2004 Pearson Addison-Wesley. All rights reserved October 27, 2006 Recursion (part 2) ComS 207: Programming I (in Java) Iowa State University, FALL 2006.
Java How to Program, 9/e © Copyright by Pearson Education, Inc. All Rights Reserved.
Chapter 13 Recursion. Topics Simple Recursion Recursion with a Return Value Recursion with Two Base Cases Binary Search Revisited Animation Using Recursion.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Chapter 7 Arrays. © 2004 Pearson Addison-Wesley. All rights reserved11-2 Arrays Arrays are objects that help us organize large amounts of information.
Slides prepared by Rose Williams, Binghamton University ICS201 Lecture 19 : Recursion King Fahd University of Petroleum & Minerals College of Computer.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Chapter 8 Recursion Modified.
Chapter 13 Recursion. Learning Objectives Recursive void Functions – Tracing recursive calls – Infinite recursion, overflows Recursive Functions that.
Chapter 4 Recursion. Copyright © 2004 Pearson Addison-Wesley. All rights reserved.1-2 Chapter Objectives Explain the underlying concepts of recursion.
Chapter 13 Recursion. Copyright © 2005 Pearson Addison-Wesley. All rights reserved. Slide 2 Overview Recursive Functions for Tasks(13.1) Recursive Functions.
Copyright © 2012 Pearson Addison-Wesley. All rights reserved. Chapter 14 Recursion.
CSIS 123A Lecture 9 Recursion Glenn Stevenson CSIS 113A MSJC.
CSE 501N Fall ‘09 12: Recursion and Recursive Algorithms 8 October 2009 Nick Leidenfrost.
11-1 Recursive Thinking A recursive definition is one which uses the word or concept being defined in the definition itself When defining an English word,
Lecture 7 b Recursion is a fundamental programming technique that can provide an elegant solution to certain kinds of problems b Today: thinking in a recursive.
Instructor: Alexander Stoytchev CprE 185: Intro to Problem Solving (using C)
Chapter 11Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 11 l Basics of Recursion l Programming with Recursion Recursion.
1 Recursion Recursion is a powerful programming technique that provides elegant solutions to certain problems. Chapter 11 focuses on explaining the underlying.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 12 Recursion.
Recursion Chapter 17 Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013.
Recursion. Objectives At the conclusion of this lesson, students should be able to Explain what recursion is Design and write functions that use recursion.
Function Recursion to understand recursion you must understand recursion.
Recursion.
Chapter 13 Recursion Copyright © 2016 Pearson, Inc. All rights reserved.
Recursion Version 1.0.
Recursion -- Introduction
CprE 185: Intro to Problem Solving (using C)
Abdulmotaleb El Saddik University of Ottawa
Recursive Thinking Chapter 9 introduces the technique of recursive programming. As you have seen, recursive programming involves spotting smaller occurrences.
Chapter 8: Recursion Java Software Solutions
Java Software Structures: John Lewis & Joseph Chase
Chapter 14 Recursion. Chapter 14 Recursion Overview 14.1 Recursive Functions for Tasks 14.2 Recursive Functions for Values 14.3 Thinking Recursively.
Recursive Thinking Chapter 9 introduces the technique of recursive programming. As you have seen, recursive programming involves spotting smaller occurrences.
Recursive Definitions
Chapter 12 Recursion (methods calling themselves)
Recursion Recursion is a fundamental programming technique that can provide an elegant solution certain kinds of problems We will focus on: thinking in.
Recursion (part 2) October 26, 2007 ComS 207: Programming I (in Java)
Java Software Solutions Foundations of Program Design Seventh Edition
Chapter 8: Recursion Java Software Solutions
Chapter 11 Recursion.
Chapter 8: Recursion Java Software Solutions
11 Recursion Software Solutions Lewis & Loftus java 5TH EDITION
Recursion (part 2) March 22, 2006 ComS 207: Programming I (in Java)
Chapter 13 Recursion Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Java Software Solutions Foundations of Program Design Sixth Edition
Presentation transcript:

1Recursion  Recursion is a fundamental programming technique that can provide an elegant solution certain kinds of problems  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

2 Recursive Thinking  A recursive definition is one which uses the word or concept being defined in the definition itself, e.g.  “A friend is a person who is a friend “  When defining an English word, a recursive definition is not effective.  But in other situations, a recursive definition can be the best way to express a concept

3 Recursive Thinking  We have used methods that call other methods to help them solve a problem.  Sometimes methods need to call themselves again.

A Simple Recursive Method 4 1. // This method does not stop - it is in an infinite loop 2. public static void forgetMeNot() 3. { 4. System.out.println(“I Miss You”); 5. forgetMeNot(); // a recursive call to itself again 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 You –…( forever!)

Writing a recursive method  Problem Statement:  The previous method does not stop executing so there is an endless loop:  Problem: Write a recursive method that:  prints “I Miss You” n times and  signs off “Love, Me”.  It will run n times 5

public class GreetingCard public class GreetingCard 1. { 2. // main method calls forgetMeNot with parameter “3” 3. public static void main(String[] args) 4. { 5. forgetMeNot(3); // invokes method for the first time 6. System.out.println(“Love, Me”); ( SPOT 1 ) 7. } 8. //*************************************************** 9. public static void forgetMeNot(int n)  // n is the number of times the message is printed. 1. { 2. if (n != 0) // base case which stop recursive calls 3. { 4. System.out.println(“I Miss You”); 5. forgetMeNot(n – 1 ); the recursive call 5. forgetMeNot(n – 1 ); // the recursive call 6. ( SPOT 2 ) // There could be more code here 7. } 8. } 6

Writing Recursive methods  Output  I Miss You  Love, Me   The recursive method forgetMeNot(...)  is called by main(...) and passed the argument “3”. 7

Main method begins with the call forgetMeNot(3): What the method does:  prints “I Miss you”  Calls forgetMeNot(2):  prints “I Miss You”  Calls forgetMeNot(1):  prints “I Miss You”  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 returns to the previous call of: forgetMeNot(0) then returns to the previous call of: forgetMeNot(1), picks up at location where it left ( SPOT 2 ) forgetMeNot(1), picks up at location where it left ( SPOT 2 ) forgetMeNot(1) has no more code after recursive call in ( SPOT 2 ) forgetMeNot(1) has no more code after recursive call in ( SPOT 2 ) Program control returns to the suspended Program control returns to the suspended forgetMeNot(2) - no more code at ( SPOT 2 ) forgetMeNot(2) - no more code at ( SPOT 2 ) con trol returns to forgetMeNot(3): con trol returns to forgetMeNot(3): Last method done so passes control back to main Last method done so passes control back to main Main: prints “Love, Me” at ( SPOT 1 ) Main: prints “Love, Me” at ( SPOT 1 ) 8

Visualization of method call s 9 1. main 2.forgetMeNot(3) 3.“I Miss You” 4.forgetMeNot(2) 5.“I Miss You” 6.forgetMeNot(1) 7.“I Miss You” 8.forgetMeNot(0) -- base case 9.return 10.Return to (1) // to where it left the method 11.Return to (2) 12.Return to (3) 13.“Love, Me” The trace is read from top to bottom as the program executes: Indentations are made every time a recursive call is made. When a method returns to where it left the calling method (AT SPOT 2) the indentation goes back to the previous level. Execution continues at the statement following the recursive call. ( SPOT 1)

10 Recursive Programming  Just because we can use recursion to solve a problem,  that does not mean this is the optimal solution.  The iterative version is easier to understand and requires less memory if N is a large number.  For instance why not just print out forgetMeNot three times in a loop??????

11 Infinite Recursion  All recursive definitions have to have a non-recursive part - a stopping case or base case  If they didn't, there would be no way to terminate the recursive path  Such a definition would cause infinite recursion  This problem is similar to an infinite loop

12Recursion  The non-recursive part is often called the base case.  e.g if (n != 0) // base case which stop recursive calls  The algorithm must ensure that the base case is reached.

Solving a Recursive Problem Recursion is based on a key problem-  divide and conquer and self-similarity.  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. 13

14Recursion  Look at the task of printing the characters of “hello”  It involves printing the first character and then the method calls itself with the first character removed.  Solving this task involves the similar task of printing hello minus the first character (look up subString method in the String class

15Recursion /* prints each character of S ( str = “hello” ) 1. public void printString(String str) 2. { 3. if( str.length() == 0 ) // base case 4. return // leave the method 5. else 6. { 7. System.out.print( str.charAt(0) ); //print first char 8. printString(str.substring(1 ));// REMOVES ONE CHAR 9. } // end of method str.substring(1) returns the string starting at “e” str.substring(1) returns the string starting at “e” For each subsequent call it removes the first character For each subsequent call it removes the first character

HELLO – PRINTING CHARACTERS  FOR INPUT OF ‘HELLO’ OUTPUT: value stored -str = “HELLO” OUTPUT: value stored -str = “HELLO”  H hello  E ello  L llo  L lo   0 O 16

17 Recursive Definitions  For any positive integer,  N is defined to be the product of all integers between 1 and N inclusive  This definition can be expressed recursively as: 1! = 1 1! = 1 N! = N * (N-1)! N! = N * (N-1)!  The factorial is defined in terms of another factorial  Eventually, the base case of 1! is reached

18 Recursive Definitions 5! 5! 5! 5 * 4! 5 * 4! 4 * 3! 4 * 3! 3 * 2! 3 * 2! 2 * 1! 2 * 1! 1 1 = BASE CASE

How recursion works  The code of a recursive method must be structured to handle both the:  base case which will end the recursive calls and  the recursive case 19

20Example  To write a method that stacks non-negative numbers to the screen vertically such as : 1234  We might break the problem into two parts: 1. Print all the digits but the last one stacked vertically 2. Print the last one. 2. Print the last one.

21 An example  To print the actual number we would 1. divide the number by 10 to get the first three digits and 2. use the mod operator to get the last digit. The pseudocode is: The pseudocode is: if the number has only one digit // base case if the number has only one digit // base case { write that digit to output write that digit to output } else { else { Write the digits of number/10 vertically Write the digits of number/10 vertically write the single digit of number % 10 - last digit write the single digit of number % 10 - last digit }

22 The WriteVertical method 1. public static void writeVertical(int number) { 1. if (number < 10) // base case 2. System.out.println(number); 2. System.out.println(number); // prints number under else 4. { 5. // divides number by 10 and calls itself again 6. writeVertical(number/10); // call itself again (no /10) // prints the last digit WHEN RECURSION UNWINDS 9. System.out.println(number % 10); 10.} 11.}

23writeVertical  The base case is : when the number has only 1 digit. when the number has only 1 digit. And then that digit is printed. And then that digit is printed. e.g. number = 4 ( 4 % 10 = 4 ) e.g. number = 4 ( 4 % 10 = 4 )  The recursive call occurs where:  // writeVertical calls itself until it reaches the base case – number < 10 // base case number < 10 // base case  // digits are printed in unwinding phase  System.out.println(number % 10);

24 public static void writeVertical(int number) { 1.public static void writeVertical(int number) { 1. if (number < 10) // base case 2.System.out.println(number); // prints numbers under System.out.println(number); // prints numbers under else { 5. writeVertical(number/10 ) ; // call itself until base case // Spot 1 – location to return to when recursion unwinds // Spot 1 – location to return to when recursion unwinds 6. System.out.println( number % 10 ); } }

25 TRACING EXECUTION (((( Activation Record for first call to superWriteVertical number: 36 When the method returns, the computation should begin at line SPOT1(line 5) of the program. Activation Record - second call to superWriteVertical number: 3 Prints out the number 3 (number is less than 10) When the method returns, the computation should begin at SPOT 1 of the program. Activation Record – returns to previous call to superWriteVertical when number is 36 The computation should begin at SPOT 1 of the program where it prints the 6

How the Activation calls work  When the recursive call to superWritevertical (36) make a call to to superWritevertical ( 3)  The number “3” is printed out.  The Activation Record for the call is popped from the stack and  Activation Record tells the computer where to re-start execution – »at SPOT 1. 26

27 Tracing Execution The record is:  superWriteVertical(36) makes a recursive call to:  superWriteVertical(3) which prints out the “3”  There is no more code so execution returns to spot1 returns to spot1 // The last line after Spot1 writes out digit 6 System.out.println( 36 % 10 ); System.out.println( 36 % 10 );

28Recursion  If another method - called method 2 - is called from within method 1,  method 1’s execution is temporarily stopped and the same information is stored for method 2.  It stores the location of the call for the second method.  It will continue to this for every recursive method call.  This information is stored in Activation Records

29 Using Recursion  Consider the task of repeatedly displaying a set of images in a mosaic that is reminiscent of looking in two mirrors reflecting each other.  The base case is reached when the area for the images shrinks to a certain size.  See MirroredPictures.java MirroredPictures.java

30 Recursion  The entire area is divided into 4 quadrants, separated by lines.  A picture of the world(with a circle indicating the Himalayan mountain section) is in the top-right quadrant.  a picture of Mt. Everest - The bottom-left quadrant contain  a picture of a mountain goat - in the bottom-right quadrant

31 Tiled Pictures

32 Repeating Pictures  In the top left quadrant contains a copy of the entire collage, including itself.  In this smaller version you can see the three simple pictures in their three quadrants.  And again, in the upper-left corner the picture is repeated (including itself). ....

33Mirrored_Images  This effect is created easily using recursion.  In the applet, the paint method invokes another method called draw pictures().  The draw_pictures() method accepts a parameter that defines the size of the area in which pictures are displayed.  It draws the three standard images using drawImage().  The draw_pictures method draws the upper left quadrant recursively.

34 public class TiledPictures extends JApplet { private final int APPLET_WIDTH = 320; private final int APPLET_HEIGHT = 320; private final int MIN = 20; // smallest picture size private Image world, everest, goat; // // Loads the images. // public void init() { world = getImage (getDocumentBase(), "world.gif"); everest = getImage (getDocumentBase(), "everest.gif"); goat = getImage (getDocumentBase(), "goat.gif"); setSize (APPLET_WIDTH, APPLET_HEIGHT); }

35 // //Performs the initial call to the drawPictures method. // public void paint (Graphics page) { drawPictures (APPLET_WIDTH, page); } } // Starts with the full size of the applet which will // be divided for every subsequent call

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. // public void drawPictures (int size, Graphics page) { // public void drawPictures (int size, Graphics page) { page.drawLine (size/2, 0, size/2, size); // vertical page.drawLine (0, size/2, size, size/2); // horizontal page.drawLine (size/2, 0, size/2, size); // vertical page.drawLine (0, size/2, size, size/2); // horizontal page.drawImage (everest, 0, size/2, size/2, size/2, this); page.drawImage (goat, size/2, 0, 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 (world, size/2, size/2, size/2, size/2, this); if (size > MIN) // if there is room to draw, call again drawPictures (size/2, page); page.drawImage (world, size/2, size/2, size/2, size/2, this); if (size > MIN) // if there is room to draw, call again drawPictures (size/2, page); }

37Mirrored_Images  On each invocation,  if the  if the drawing area is large enough  the draw_pictures method is invoked again, using a smaller drawing area.  Eventually the drawing area becomes so small that the recursive call is not performed.

Halving the size of the picture  Each time the draw-pictures method is invoked,  the size passed as a parameter is used to determine the area in which the pictures are presented  relative to the co-ordinates  relative to the co-ordinates 38

39 Drawing Mirrors  The drawImage method automatically scales the pictures to fit in the area indicated.  The base case of the recursion in this problem specifies a minimum size for the drawing area.  Because the size is decreased each time,  eventually the base case is reached and the recursion stops.  That is why the last upper left corner is empty in the smallest version of the collage.

40 Maze Traversal We can use recursion to find a path through a maze  From each location, we can search in each direction  Recursion keeps track of the path through the maze  The base case is an invalid move or reaching the final destination  See MazeSearch.java MazeSearch.java  See Maze.java Maze.java

41 Using Recursion  A maze is solved by trial and error –  choosing a direction,  following a path,  returning to a previous point if the wrong move is made.  As such, it is another good candidate for a recursive solution.

In Maze_Search.java,  a 2-D array of integers filled with 0’s and 1’s.  A ‘1’ indicates a clear path and a ‘0’ a blocked path. a ‘0’ a blocked path.  As the maze is solved these parameters are changed  to other values (3,1) to  indicate attempted and successful paths through the maze. 42

43 // Class Maze represents a maze of characters. The goal is to get // from the top left corner to the bottom right, following a path // of 1's. class Maze { 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}};

44 Recursion - Maze  The only valid moves are right, left, up and down right, left, up and down with no diagonal moves allowed. with no diagonal moves allowed.  The goal is to start in the upper-left corner of the maze (0,0) and find a path that reaches the  bottom-right corner.

Maze_Search class  The Maze_Search class contain the main method which instantiates the maze and prints out it as a matrix.  It solves the maze if possible and  prints out the solved version of the maze. 45

Traverse – determines valid moves  The recursive method traverse ()returns a boolean value that indicates whether a solution was found.  First the method determines if a move to that row and column is valid.  A move is considered valid if: 1. It stays within the grid 1. It stays within the grid 2. if the grid contains a ‘1’ in that cell 2. if the grid contains a ‘1’ in that cell 46

47 Recursion  The initial call to traverse passes in the upper-left location(0,0).  If the move is valid,  the grid entry is changed from a 1 to a 3  marking this location as visited so that later we don’t retrace out steps. so that later we don’t retrace out steps.

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 = 0 && row < grid.length && column >= 0 && column = 0 && column < grid[0].length) // check if cell is not blocked and not previously tried // check if cell is not blocked and not previously tried if (grid[row][column] == 1) if (grid[row][column] == 1) result = true; result = true; return result; return result; } // method valid

49 Then the traverse method determines if the maze has been completed -- by having reached the bottom right location of the maze. by having reached the bottom right location of the maze. The 3 possibilities for the base case for each recursive call are: The 3 possibilities for the base case for each recursive call are: 1. an invalid move because it is out of bounds 1. an invalid move because it is out of bounds 2. an invalid move because it has been tried before (it contains a 3) so we go back to a previous cell 2. an invalid move because it has been tried before (it contains a 3) so we go back to a previous cell 3. a move that arrives at the final location – Success! 3. a move that arrives at the final location – Success!

50 // Recursively traverse the maze. and inserts special characters indicating locations that have been tried and that eventually become part of the solution. public boolean traverse (int row, int column) { boolean done = false; boolean done = false; if (valid (row, column)) // calls method to determine the cell holds a 1 if (valid (row, column)) // calls method to determine the cell holds a 1 { grid[row][column] = 3; // marks cell as tried and sets it to 3 grid[row][column] = 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; // maze is solved,we have reached the end done = true; // maze is solved,we have reached the end else else { done = traverse (row+1, column); // move down as far as possible done = traverse (row+1, column); // move down as far as possible if (!done) // if that did not work, if (!done) // if that did not work, done = traverse (row, column+1); // move right done = traverse (row, column+1); // move right if (!done) // if that did not work, if (!done) // if that did not work, done = traverse (row-1, column); // move up done = traverse (row-1, column); // move up if (!done) // if that did not work, if (!done) // if that did not work, done = traverse (row, column-1); // move left done = traverse (row, column-1); // move left } if (done) // part of the final path - this is marked when the calls unwind if (done) // part of the final path - this is marked when the calls unwind grid[row][column] = 7; // this marks the path to the final solution grid[row][column] = 7; // this marks the path to the final solution } // closes if valid } // closes if valid return done; return done; } // method traverse

51 Mazes  If the current location is not the bottom-right corner which is where the we want to go to,  we search for a solution in each of the primary directions. Down, Right,Up and Left  First, we look down by recursively calling the traverse method and passing in the new location  The logic of the solve methods starts all over again using this new position.

52Mazes  A solution is found by either starting down from the current location or it is not found.  If it’s not found, we try moving right, then up. moving right, then up.  Finally if no direction yields a correct path we try left. we try left.  If no direction from this location yields a correct solution,  then there is no path from this location and the traverse method returns false.

53Maze_Search  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.

SOLUTION Therefore, when the final maze is printed: The locations left on the stack are part of the solution. 1. the zeros still indicate a blocked path and 2.A 1 indicates an open path that was never tried 3.A 3 indicates a path that was tried but failed to yield a correct solution 4. A 7 indicates a part of the final solution of the maze 54

55Maze_Search  Maze_Search Solution moves are down right up and left  The yellow marks a false path – that is we could not move in any direction when backtracking - look at the path of 3’s

56 Fractals  Fractals are very complex pictures generated by a computer from a single formula.  Very often they are very colorful and look beautiful.  A fractal gets created by using iterations.  This means that one formula is repeated with slightly different values over and over again,  taking into account the results from the previous iteration.

57Fractals  The results are then graphed.  In fractals, the little parts of them look like the big picture, and  when one zooms in closer,  one will find more and more repeating copies of the original. repeating copies of the original.

58Fractals  A fractal is a geometric shape made up of the same pattern repeated in different sizes and orientations  The Koch Snowflake is a particular fractal that begins with an equilateral triangle  To get a higher order of the fractal, the sides of the triangle are replaced with angled line segments

Fractals 59  Fractals are used in graphics to  artificially produce natural scenes such as mountains, clouds trees and others objects.  Basically, a line segment is raised in the middle and moved vertically a random distance.  The end points remain in the same place.

60Fractals  The order below is order 2  ( the line is broken into two segments).  Now, we have two smaller segments of the same line.

61Fractals  By repetitively grabbing the midpoint of each line segment and  moving it up or down some random distance,  the line becomes ever more jagged.  After many steps a ragged line is created that approximates a picture of an island or a cloud or the approximates a picture of an island or a cloud or the tops of mountains. tops of mountains. ....

Fracta;s  If we magnified any given segment of the line,  it would look like a small portion of the whole line. 62

63Fractals  two locations of the endpoints of the original line.  To create a method, we must input the two locations of the endpoints of the original line. two locations of the endpoints of the original line. To create a method, we must input the two locations of the endpoints of the original line.  top side and left side  Distances are measured from the top side and left side of the drawing area. top side and left side Distances are measured from the top side and left side of the drawing area.   E.g. coordinates for x = 100, y = 55 E.g. coordinates for x = 100, y = 55 Distances are measured from the top side and left side of the drawing area Horizontaldistance 100,55

64 Method randomFractal public static void randomFractal( int leftx, int leftY) { int rightx; int rightY; Graphics drawArea;// instance variables int rightx; int rightY; Graphics drawArea;// instance variables if (rightX - leftX <= STOP) // area too small to draw – base case if (rightX - leftX <= STOP) // 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; // divide x in half midX = (leftX + rightX) \2; // divide x in half midY = (leftY + rightY) \2; // divide y in half midY = (leftY + rightY) \2; // divide y in half

(con’d) // calculate degree of variation in line size – delta delta = (int) (Math.random() - 0.5) * (rightX - leftX); delta = (int) (Math.random() - 0.5) * (rightX - leftX); midY += delta; // add random value to y midY += 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, drawArea ); randomFractal(leftX, leftY,midX, midY, drawArea ); randomFractal(midX, midY,rightX, rightY, drawArea); randomFractal(midX, midY,rightX, rightY, drawArea); } // close method 65

66 Fractals- ANALYSIS OF LINE leftX, leftY (70, 60) rightX, rightY (270, 35) (270, 35) midX and midY = The midpoint of the line. (170 & 47) midX = (leftX + rightX) /2 midX = (leftX + rightX) /2  The y-midpoint must be shifted up or down a random amount –  this shift IS NO MORE than half the distance from leftX and leftY.  The result is stored in delta: delta = (int) (Math.random() - 0.5) * (rightX - leftX); midX,midY (170, 47)

67Fractals  The call to random produces a number from -0.5 to 0.5.  The result is rounded to an integer.   Then the result is added to midY: midY += delta. midY += delta. Now we have two segments: 1. From the left end point of the original segment to the displaced midpoint. 1. From the left end point of the original segment to the displaced midpoint. 2. From the midpoint to the right endpoint. 2. From the midpoint to the right endpoint.

Fractals  To create a random fractal for each of these segments,  we use two recursive calls. 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 line 68

69Fractals 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 left endpoints of the original segment  and the right coordinates of the leftmost segment or the midpoint of the original segment.  The second recursive call handles the right segment of the original line.

70Fractals  Now, we have to find a stopping case.  The stopping case should be when the  leftX and rightX get too close.  At this point we draw a line: if(rightX - leftX <= STOP) drawArea.drawLine(leftX, leftY,rightX, rightY);

71 Koch Snowflakes Becomes

72 Koch Snowflakes

73 Koch Snowflakes

74 Towers of Hanoi  The Towers of Hanoi is a puzzle made up of 1. three vertical pegs and 1. three vertical pegs and 2. several disks that slide on the pegs 2. several disks that slide on the pegs  The disks are of varying size, initially placed on one peg  The largest disk IS on the bottom with increasingly smaller ones on top

TOWERS OF HANOI  The goal is to move all of the disks from one peg to another under the following rules: We can move only one disk at a timeWe can move only one disk at a time We cannot move a larger disk on top of a smaller oneWe cannot move a larger disk on top of a smaller one 75

76 Towers of Hanoi  An iterative solution to the Towers of Hanoi is quite complex  A recursive solution is much shorter and more elegant  See SolveTowers.java SolveTowers.java  See TowersOfHanoi.java TowersOfHanoi.java  Read Chapter 4.3 in your text for a very good explanation of the Towers OF HANOI

77 Tower Of Hanoi  Goal: Move all disks from A to C  Rule: No bigger disk is on top of smaller disk at any timeNo bigger disk is on top of smaller disk at any time Move one disk at a timeMove one disk at a time A B C 4 disks

78 Recursive Code For Hanoi Tower N = number of disks void move(int n, char start, char finish, char buf) {if(n==1) System.out.println(“Move from”+start+“ to”+finish); System.out.println(“Move from”+start+“ to”+finish);else{ 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);}}

79 4-disk Example A B C

80 4-disk Example A B C

81 4-disk Example A B C

82 Demo Of Hanoi  A nice animation of Hanoi online:

83 Don't look down  When you write or debug a recursive function, think about this level only  Wherever there is a recursive call, assume that it works correctly  If you can get this level correct,  you will automatically get all levels corre ct  You really can't understand more than one level at a time,  so don’t even try