Recursion Continued - PowerPoint PPT Presentation

1 / 23
About This Presentation
Title:

Recursion Continued

Description:

Our backtracking in the maze earlier, we can use recursion to do the ... catch (IOException e) { // exit on an IOException. e.printStackTrace(); System.exit(0) ... – PowerPoint PPT presentation

Number of Views:48
Avg rating:3.0/5.0
Slides: 24
Provided by: geraldh6
Category:

less

Transcript and Presenter's Notes

Title: Recursion Continued


1
Recursion -- Continued
  • March 29, 2005

2
We Can Use Recursion to Do Backtracking
  • Our backtracking in the maze earlier, we can use
    recursion to do the same thing without an
    (explicit) stack.
  • The actual layout of the program may not change
    much

3
Some Questions?
  • What's the base case?
  • What are the general cases?

4
Amazing the Class
  • import java.io.
  • import java.util.
  • / _at_author Jerry Heuring March 27, 2005
    This is an example of doing backtracking using
    recursion rather than an "explicit" stack. It
    is similar to what you probably did in project
    3. /
  • public class Amazing
  • private char maze
  • // The following values are constants. They//
    cannot be changed and are used as values// so
    that the symbol can be easily changed// or
    updated in the application.
  • final public static char OPEN ' ', WALL'X',
    MOUSE'M', VISITED'V', CHEESE'C'
  • //The important spots in the maze and the size
    of the maze.
  • private int columns, rows, goalRow, goalColumn,
    startRow, startColumn

5
  • / The constructor will attempt to read the
    maze in from a file "maze.txt". The format is
    pretty much set and it does not react well to
    errors. In addition, the constructor locates
    the starting and goal positions and stores them
    in the appropriate instance variables./
  • public Amazing()
  • // Initialize the Maze -- I'm going to just
    read it in
  • // as two lines representing rows and columns
    and then
  • // one row per line.
  • try
  • BufferedReader reader new BufferedReader(
    new FileReader("maze.txt"))
  • String line
  • rows Integer.parseInt(reader.readLine())
  • columns Integer.parseInt(reader.readLine())
  • maze new char rowscolumns

6
  • for (int row 0 row lt rows row) line
    reader.readLine() for (int col 0 col lt
    columns col) mazerowcol
    line.charAt(col) if (mazerowcol
    CHEESE) // Check if this is the
    goal goalRow row goalColumn
    col else if (mazerowcol MOUSE)
    // Check if this is the mouse!
  • startRow row startColumn
    col catch (NumberFormatExceptio
    n e) // exit if we get an invalid
    number e.printStackTrace() System.exit(0)
    catch (FileNotFoundException e) // exit if
    the file is not there e.printStackTrace() Sys
    tem.exit(0) catch (IOException e) // exit
    on an IOException e.printStackTrace() System.
    exit(0)

7
  • /
  • This routine starts out the recursion. The
    recursive
  • function is actually FindCheese but we need
    to start
  • off at the correct starting position.
  • /
  • public void findPath()
  • if (findCheese(startRow, startColumn))
  • System.out.println("Found Path")
  • else // It's possible that there isn't a
    path
  • System.out.println("Can't find Path")

8
  • /
  • This is the recursive routine that will do
    our backtracking
  • and eventually, if possible, find the cheese.
  • Since the maze is not pushed and popped onto
    and off of the
  • stack it must be restored after the attempted
    move.
  • _at_param currentRow The row that the "mouse"
    is at
  • _at_param currentColumn The column that the
    "mouse" is at
  • _at_return true if the cheese is found, false
    otherwise
  • /
  • public boolean findCheese (int currentRow, int
    currentColumn)
  • if (currentRow goalRow currentColumn
    goalColumn)
  • System.out.println(currentRow ", "
    currentColumn) return true

9
  • / Try going north/up /
  • if (mazecurrentRow - 1currentColumn
    OPEN mazecurrentRow-1currentColumn
    CHEESE ) mazecurrentRowcurrentColumn
    VISITED if (findCheese(currentRow-1,
    currentColumn)) System.out.println(currentRow
    ", " currentColumn)
  • return true mazecurrentRowcurrentCol
    umn OPEN
  • / Try going south/down / if (mazecurrentRow
    1currentColumn OPEN mazecurrentRow1
    currentColumn CHEESE)
  • mazecurrentRowcurrentColumn
    VISITED if (findCheese(currentRow1,
    currentColumn)) System.out.println(currentRow
    ", " currentColumn) return
    true mazecurrentRowcurrentColumn
    OPEN

10
  • / Try going west/left/ if (mazecurrentRowc
    urrentColumn-1 OPEN mazecurrentRowcur
    rentColumn-1 CHEESE) mazecurrentRowcurr
    entColumn VISITED if (findCheese(currentRow,
    currentColumn-1)) System.out.println(current
    Row", " currentColumn) return
    true mazecurrentRowcurrentColumn
    OPEN / Try going east/right / if
    (mazecurrentRowcurrentColumn1 OPEN
    mazecurrentRowcurrentColumn1 CHEESE)
    mazecurrentRowcurrentColumn VISITED
  • if (findCheese(currentRow, currentColumn1))
    System.out.println(currentRow ", "
    currentColumn) return true mazecurrent
    RowcurrentColumn OPEN

11
  • /
  • If we reach this point nothing worked --
    return
  • a false...
  • /
  • return false
  • /
  • The main program. Simply creates/instantiates
    the
  • object and tried to find the path.
  • _at_param arguments
  • /
  • public static void main (String arguments)
  • Amazing test new Amazing()
  • test.findPath()
  • System.exit(0)

12
Linked Lists
  • In many cases, a linked list is considered a
    recursive structure. It is an element with a
    linked list attached.
  • This means that we can easily express some common
    operations as recursive methods in Java.

13
Searching
  • public boolean search (LinkedListElement head,
    String value) if (head null)
    return false else if (((String)head.getBody(
    )).equals(value)) return true else
    return search(head.getNext( ), value)

14
Printing
  • public void output ( LinkedListElement head) if
    (head null) return else
    System.out.println ((String)(head.getBody ( )
    )) output(head.getNext( ))

15
Counting
  • public int size (LinkedListElement head ) if
    (head null) return 0 else return 1
    size(head.getNext( ))

16
Recursion vs. Iteration
  • You can do anything you need via recursion and
    iteration.
  • Recursion tends to have a bit more overhead due
    to what needs to happen when a method is called.
  • Use the most appropriate method.
  • How do you know? Experience for the most part

17
What is Happening?
  • Underneath everything the system is keeping a
    stack!
  • Its stack has the variables (primitive types and
    not objects passed) as well as any variables
    local to the routine and the location to return
    to in the routine.
  • You will deal more with the low level details of
    what goes on in EECS 2100.

18
Project 4 and Beyond
  • We will delay until Tuesday April 5, 2005
  • Project 5 will come out Thursday regardless.

19
Grammars
  • A grammar is a way of describing a language. For
    example an English sentence could consist of a
    noun phrase followed by a verb phrase.
  • Productions are used to describe these
  • Two types of symbols, non-terminals and
    terminals. Terminals can not be expanded further.

20
Sample Grammar
  • Sentence -gt NounPhrase VerbPhrase
  • NounPhrase-gt "The Boy" "The Girl" "Jane"
    "Dick" "Spot"
  • VerbPhrase -gt "runs away" Modification " is
    sleeping"
  • Modification -gt "sees" NounPhrase Action
  • Action -gt "sleeping" "running" "playing"
    "studying" "eating"
  • Possible Sentences
  • The Boy runs away
  • Jane sees The Girl running
  • Dick sees Dick running
  • The Boy sees Spot studying

21
Generating Sentences
  • One could set this up as a sentence generator
    and, with a few more productions, they could set
    it up to write a short story. We are going to
    read in an arbitrary set of productions and
    generate random paragraphs or stories.

22
Grammars
  • In the grammars there will be no or's we will
    have multiple productions instead.
  • Non-terminals will be enclosed in lt gt/'s
  • terminals will be enclosed in double quotes.
  • Example
  • ltSentencegt ltNoun Phrasegt ltVerb Phrasegt
  • ltNoun Phrasegt "The boy"
  • ltNoun Phrasegt "The girl"
  • ltNoun Phrasegt "Jane"
  • ltNoun Phrasegt "Dick"
  • ltNoun Phrasegt "Spot"

23
You May Want To Use Some Special Java Classes
  • StringTokenizer can help in breaking up strings.
    You can specify which character or characters end
    the pieces of the String you want and return just
    the next token.
  • We will need Random again to pick between
    different productions.
  • We will want to use a HashMap to speed up looking
    for production rules.
Write a Comment
User Comments (0)
About PowerShow.com