EXAMPLES OF RECURSION - PowerPoint PPT Presentation

1 / 35
About This Presentation
Title:

EXAMPLES OF RECURSION

Description:

Good exercise: Try to write the FUNCTION. Attack which is used in the book, but not ... AB/CD- The '.' operator is commonly used in string algorithms to stand ... – PowerPoint PPT presentation

Number of Views:438
Avg rating:3.0/5.0
Slides: 36
Provided by: niroo
Category:

less

Transcript and Presenter's Notes

Title: EXAMPLES OF RECURSION


1
  • 1
  • EXAMPLES OF RECURSION
  • Towers of Hanoi
  • Writing Linked Lists Backwards
  • Recursive Insert
  • 8 Queens
  • Recognizing Simple Languages
  • Prefix Expressions
  • Conversion Prefix to Postfix

2
  • 2
  • How do we transfer all disks from A to C, with
    the following limitations
  • 1) Only one disk at a time may be moved.
  • 2) A larger disk may never lie on a smaller
    disk.
  • The solution is simple and recursive
  • Basic idea
  • 1) Transfer recursively all but the largest disk
    from A to the temporary
  • peg B.
  • 2) Transfer the largest disk from A to C.
  • 3) Transfer recursively all disks from B to C.

C
B
A
3
  • 3
  • NOTE
  • While you are transferring n-1 disks from A to
    B, you are using C as a
  • temporary storage. While you are transferring
    n-1 disks
  • from B to C, you are using A as a temporary
    storage.
  • Thats it. It is that simple.
  • void tow (int cnt, char src, char dst, char spr)
  • if (cnt 1)
  • cout ltlt src ltlt --gt ltlt dst ltlt endl
  • else
  • tow (cnt-1, src, spr, dst)
  • tow (1, src, dst, spr)
  • tow (cnt-1, spr, dst, src)

4
4
  • EXAMPLE

NOTE This would work with 3 pegs, even if there
are 4, 5, 6, 7, ... disks! (the pegs just have to
be higher. 8-) -) ). The solution is completely
general.
5
Display the String 5
  • You want to write the characters in the string in
    the order in which they appear in the linked
    list
  • struct str
  • char data
  • struct str next
  • void writeString(struct str ptr)
  • if (str ! NULL)
  • cout ltlt str data ltlt endl
  • writeString(str next)

6
6
  • Writing Linked Lists Backward (recursively)
  • Writing this program is very hard iteratively.
  • Its very easy recursively

  • struct str
  • char data
  • struct str next
  • void writeback(struct str ptr)
  • if (str ! NULL)
  • writeback (str next)
  • cout ltlt str data ltlt endl

7
  • Assume that data is now a single character!

7
head
T
NULL
C
A
Writeback(head)
str
str
str
str
First call
2nd call
3rd call
Last call
8
Strip a way first character 8
  • writeBackward2(in sstring)
  • cout ltlt Enter writBackward2 with string
  • ltlt sltlt endl
  • if (the string is empty)
  • Do nothing this is the base case
  • else
  • ( writedBackward2 (s minus its character ) //
    calling point
  • cout ltlt About to write first character of
    string
  • ltlt s ltlt endl
  • write the first character of s
  • cout ltlt leave writeBackward2 with string
  • ltlt s ltlt endl

9
  • 9
  • Insert Revisited
  • We will now redo insert into sorted linked
    list. This time recursively. It turns out that
    this is simpler than iterative insert. This
    eliminates the need for trailing pointer and a
    special case for inserting into the beginning of
    the list
  • void Insert (struct node L, int X)
  • if ((L NULL) (X lt L data))
  • struct node p new node
  • p data X
  • p next L
  • L p
  • else Insert (L next, X)

10
  • 10

Example
head
12
4
8
10
x
Example
head
12
4
8
2
x
11
  • The 8 Queens Problem
  • We will solve the 8 Queens problem using
  • BACKTRACKING. Actually we will solve
  • the n Queens problem.
  • What is BACKTRACKING?
  • What is the 8 Queens problem?
  • What is the n Queens problem?

12
  • Backtracking
  • Backtracking is kind of solving a problem by
    trial and error. However, it is a well organized
    trial and error. We make sure that we never try
    the same thing twice.
  • We also make sure that if the problem is finite
    we will eventually try all possibilities
    (assuming there is enough computing power to try
    all possibilities).

13
  • The 8 Queens Problem
  • Given is a chess board. A chess board has
  • 8x8 fields. Is it possible to place 8 queens on
  • this board, so that no two queens can attack
  • each other?
  • NOTES A queen can attack horizontally,
    vertically, and on both diagonals, so it is
    pretty hard to place several queens on one
  • board so that they dont attack each other.
  • Q

14
  • The n Queens problem
  • Given is a board of n by n squares.
  • Is it possible to place n queens (that behave
    exactly like chess queens) on this board, without
    having any one of them attack any
  • other queen?
  • Example 2 Queens problem is not solvable.
  • Example 2 The 4-queens problem is solvable

15
  • Basic idea of solution
  • Start with one queen in the first column, first
    row.
  • Start with another queen in the second column,
    first row.
  • Go down with the second queen until you reach a
  • permissible situation.
  • Advance to the next column, first row, and do the
    same thing.
  • If you cannot find a permissible situation in
    one column and reach the bottom of it, then you
    have to go back to the previous column and move
    one position down there.
  • (This is the backtracking step.)
  • If you reach a permissible situation in the
    last column of the board, then the problem is
    solved.
  • If you have to backtrack BEFORE the first
    column, then the problem is not solvable.

15
16
  • 16

illegal
illegal
illegal
illegal
legal
illegal
I cannot go further down in row 3. I cannot go
further down in row 3. I must backtrack!
However, I can not go further down in column 2
either. I must backtrack one more step.
17
  • 17
  • Now I start in the second column.

Q
Q
18
  • 18
  • At this point I am at the end of the first
    column. I would have to backtrack again, but
    thats impossible, so the problem is unsolvable.

Q
Q
Q
Q
Q
Q
Q
Q
Q
backtrack
illegal
illegal
illegal
Q
Q
Q
Q
Q
Q
Q
Q
Q
Q
Q
Q
Q
Q
Q
illegal
legal
illegal
illegal
bkt/ill
ill/end
19
  • 19
  • We will work out a successful example also
  • QQ Q Q QQ Q Q
  • Q Q
  • Q Q Q QQ
  • Illegal illegal legal illegal illegal
    illegal
  • Q QQ Q Q Q
  • Q
  • Q Q
  • Q Q Q Q QQ
  • Illegal illegal illegal illegal
    illegal

20
  • 20
  • Backtrack to column 2. Then backtrack to column
    1. Then go down in column 1.
  • Q 3 Q QQ Q Q
  • Q ill Q Q Q QQ Q
  • steps Q
  • Q Q Q Q Q
  • Illegal ill
    ill legal
  • I placed 4 queens on a 4X4 board.
  • Problem solved.

21
21
  • Are there other solutions? There must be, due to
    symmetry
  • We can continue the program
  • to find this and other solutions.
  • The program is long and complicated. It certainly
  • does not fit onto one screen. It moves from
  • one row to the next row with a while loop.
    However,
  • it moves from one column to the next column by
  • recursion. This is done as follows

22
22
  • void PlaceNextQueen (int Column, boardtypes
    Board, boolean Done)
  • ..............
  • ..............
  • PlaceNextQueen(Column1, Board, Done)
  • Please study the program in your textbook.
  • Good exercise Try to write the FUNCTION
  • Attack which is used in the book, but not
  • explained. Attack(Board, Row, Column)
  • returns TRUE if on the board there is any queen
  • that can attack the field in row Row and column
  • Column.

23
  • Recognizing Simple Languages 23
  • A LANGUAGE is a set of strings and symbols.
  • A GRAMMAR is a set of rules that defines legal
    sentences of a language.
  • A recognizer is a program that incorporates a
  • grammar. It takes as input a string and returns
    TRUE if the string conforms to the rules of the
    grammar, and FALSE otherwise.
  • Notation
  • ltsomethinggt means that the something is a
  • variable of the grammar.
  • XY means that we can choose X or Y

24
  • Example
  • ltnumbergt ltdigitgt ltnumbergt ltdigitgt
  • ltdigitgt 0 1 2 3 4 5 6 7 8 9
  • A number is either a digit or it is another
    number followed by a digit.
  • A digit is either 0 or 1 or a 2 or a... or a 9.
    Reminder A valid C identifier consists of one
    or more digits or letters or _. However,the first
    character must be a letter or _. First
  • the grammar
  • ltidentifiergt
  • ltlettergt ltunderscoregt ltidentifiergt ltlettergt
    ltidentifiergt ltdigitgt ltidentifiergt ltunderscoregt

24
25
  • ltlettergt A B C ..... Z a b c ...
    z
  • ltdigitgt 0 1 2 3 4 5 6 7 8 9
  • ltunderscoregt _
  • boolean Id(char w, int length)
  • if (length 1)
  • if ( / w0 is a letter or underscore/)
  • return boolean(1)
  • else return boolean(0)
  • else if ( / wlength-1 is a letter or _ /)
  • return Id(w,length-1)
  • else if ( / wlength-1 is a digit /)
  • return Id(w,length-1)
  • else return boolean(0)

25
26
Palindromes 26
  • Example RADAR, DEED, MADAM IM ADAM
  • ltpalgt ltemptygt ltchgt a ltpalgt a b ltpalgt b
    ...
  • ltchgt a b c ...
  • ltemptygt
  • Note We have to specify all the ...!
  • boolean Pal(char w, int first, int last)
  • if ( (last - first) lt 0) // 1 or 0 elements
  • return boolean(1)
  • else if ( wfirst wlast )
  • return Pal(w, first1, last-1)
  • else
  • return boolean(0)

27
  • The language
  • a n b n
  • Examples ab n 1
  • aabb n 2
  • aaaabbbb n 4
  • ltlegalwordgt ltemptygt a ltlegalwordgt b
  • ltemptygt

27
28
  • boolean recognize(char w, int first, int last)
  • if ((last - first) lt 0) // length is zero
  • return boolean(1)
  • else if ((wfirst a)(wlast b))
  • return recognize(w, first1, last-1)
  • else
  • return boolean(0)

29
INFIX, PREFIX, and POSTFIX 29
  • Normal Infix
  • a b
  • a b c
  • (a b) c
  • We use priorities and parentheses to make this
  • unambiguous.
  • PREFIX
  • a b
  • a b c
  • POSTFIX
  • a b
  • a b c 14

30
  • ltpost-expgt ltlettergt
  • ltpost-expgt ltpost-expgt ltoperatorgt
  • ltoperatorgt - /
  • ltlettergt ... as before
  • Now we want a program that can recognize a
  • prefix expression.
  • 15
  • Very simplified, this is what we do We look
  • for the end of a prefix expression in an array.
  • If the end is 0, then there is no prefix
  • expression.
  • To find the end of a prefix expression, we
  • look for an operator, and then we look for the
  • end of two more prefix expressions, because
  • every operator requires two prefix
  • expressions.

31
  • int end(char S, int first, int last)
  • if ((first lt 0) (first gt last))
  • return -1
  • else if (/Sfirst is a letter/)
  • return first
  • else if (/Sfirst is an operator/)
  • int tmp end(S, first1, last)
  • if (tmp gt 0)
  • return end(S, tmp1, last)
  • else
  • return -1

32
  • Converting Prefix to Postfix
  • Basic idea
  • ltopgt ltpre1gt ltpre2gt
  • must become
  • ltpost1gt ltpost2gt ltopgt
  • AND
  • ltpre1gt must become ltpost1gt
  • ltpre2gt must become ltpost2gt
  • Example
  • conv(/AB-CD) ---gt
  • conv( /AB -CD) ---gt
  • conv(/AB) conv(-CD) ---gt
  • conv(A) conv(B) / conv(C) conv(D) - ---gt
  • A B C D -
    ---gt
  • AB/CD-

33
  • The . operator is commonly used in string
    algorithms to stand for concatenation.
  • AB . CD is therefore ABCD
  • (However, in grammar expressions the . is
    usually not written.)
  • Very rough algorithm
  • expr Convert(expr)
  • if (/expr is a single letter/)
  • return expr
  • else
  • return ( Convert(findpref(expr)) .
  • Convert(findpref2(expr)) .
  • operatorof(expr) )

34
Proof of EY not a prefix Expression 34
  • If E is a prefix expression, then EY is not a
    prefix expression for any nonempty Y (i.e., a
    prefix expression cannot be the initial substring
    of another prefix expression.) We will give a
    proof by induction on E the number of
    characters in E.
  • Basis E 1 Definition of prefix implies E is
    a single letter and definition of prefix implies
    EY must begin with an operator. 
  • Inductive hypothesis For all E with 1 lt E lt n
    and for all nonempty Y, if E is prefix, then EY
    is NOT prefix.
  • Inductive step Say E n, then E op E1 E2
    for some E1 and E2, which implies that E1 and E2
    are prefix expressions and that E1 , E2 lt
    n. If EY is prefix for some Y, then EY op W1
    W2 for some W1 and W2, and W1 and W2 are prefix
    expressions

35
Proof of E Y not a prefix Expression 35
  • We claim that E1 W1 if not, then one is a
    substring of the other, so both cannot be a
    prefix by inductive hypothesis (E1 lt n).
  • Summarizing what we have so far
  • E op E1 E2
  • and
  • E op W1 W2
  • E op E1 W2
  • E op E1 E2 Y
  •  
  • But this implies that W2 E2Y, which cannot be
    because E2 and W2 are both prefixes and E2 is an
    initial substring of W2.
Write a Comment
User Comments (0)
About PowerShow.com