COSC 2007 Data Structures II Chapter 6 Recursion

  • Slides: 36
Download presentation
COSC 2007 Data Structures II Chapter 6 Recursion as a Problem-Solving Technique

COSC 2007 Data Structures II Chapter 6 Recursion as a Problem-Solving Technique

Topics 2 n 8 -Queen problem n Languages n Algebraic expressions n Prefix &

Topics 2 n 8 -Queen problem n Languages n Algebraic expressions n Prefix & Postfix notation & conversion

Introduction n Backtracking: n n A problem-solving technique that involves guesses at a solution,

Introduction n Backtracking: n n A problem-solving technique that involves guesses at a solution, backing up, in reverse order, when a dead-end is reached, and trying a new sequence of steps Applications 8 -Queen problems n Tic-Tac-Toe n 3

Eight-Queens Problem n Given: n n n Required: n 4 64 square that form

Eight-Queens Problem n Given: n n n Required: n 4 64 square that form 8 x 8 - rows x columns A queen can attack any other piece within its row, column, or diagonal Place eight queens on the chessboard so that no queen can attack any other queen

Eight-Queens Problem n Observations: n Each row or column contain exactly one queen n

Eight-Queens Problem n Observations: n Each row or column contain exactly one queen n There are 4, 426, 165, 368 ways to arrange 8 queens on the chessboard n n Wrong arrangements could be eliminated to reduce the number of solutions to the problem n n 5 Not all arrangements lead to correct solution 8! = 40, 320 arrangements Any idea?

Eight-Queens Problem n Solution Idea: n n 6 Start by placing a queen in

Eight-Queens Problem n Solution Idea: n n 6 Start by placing a queen in the first square of column 1 and eliminate all the squares that this queen can attack At column 5, all possibilities will be exhausted and you have to backtrack to search for another layout When you consider the next column, you solve the same problem with one column less (Recursive step) The solution combines recursion with backtracking

Eight-Queens Problem n How can we use recursion for solving this problem? n For

Eight-Queens Problem n How can we use recursion for solving this problem? n For placing a queen in a column, assuming that previous queens were placed correctly a) b) c) n Base case: n n 7 If there are no columns to consider Finish – Base case Place queen successfully in current column Proceed to next column, solving the same problem on fewer columns – recursive step No queen can be placed in current column Backtrack Either we reach a solution to the problem with no columns left Success & finish Or all previous queens will be under attack Failure & Backtrack

Eight-Queens Problem n 8 Pseudocode Place. Queens (in curr. Column: integer) // Places queens

Eight-Queens Problem n 8 Pseudocode Place. Queens (in curr. Column: integer) // Places queens in columns numbered Column through 8 if (curr. Column > 8) Success. Reached a solution // base case else { while (unconsidered squares exist in the curr. Column & problem is unsolved) {determine the next square in column “curr. Column” that is not under attack in earlier column if (such a square exists) { Place a queen in the square Place. Quenns(curr. Column + 1) // Try next column if ( no queen possible in curr. Column+1) Remove queen from curr. Column & consider next square in that column } // end if } // end while } // end if

Eight-Queens Problem n Implementation: n Classes: n n Queen. Class Data members n board:

Eight-Queens Problem n Implementation: n Classes: n n Queen. Class Data members n board: n n square n 9 How? Indicates that the square has a queen or is empty

Eight-Queens Problem n Implementation: n Methods needed: n Public functions (methods) n n Private

Eight-Queens Problem n Implementation: n Methods needed: n Public functions (methods) n n Private functions (methods) n n n 10 Clear. Board: Sets all squares to empty Display. Board: Displays the board Place. Queens: Places the queens in board’s columns & returns either success or failure Set. Queen: Sets a given square to QUEEN Remove. Queen: Sets a given square to EMPTY Is. Under. Attack: Checks if a given square is under attack Index: Returns the array index corresponding to a row or column Textbook provides partial implementation

Languages n Language: n A set of strings of symbols n Can be described

Languages n Language: n A set of strings of symbols n Can be described using syntax rules n Examples: n Java program n program = { w : w is a syntactically correct java program} n Algebraic expressions n 11 Algebraic Expression = { w : w is an algebraic expression }

Languages n Language recognizer: n n Recognition algorithm: n n 12 A program (or

Languages n Language recognizer: n n Recognition algorithm: n n 12 A program (or machine) that accepts a sentence and determines whether the sentence belongs to the language An algorithm that determines whether a given string belongs to a specific language, given the language grammar If the grammar is recursive, we can write straightforward recursive recognition algorithms

Languages n Example: Grammar for Java identifiers Java Ids = {w: w is a

Languages n Example: Grammar for Java identifiers Java Ids = {w: w is a legal Java identifier} n Grammar < identifier > = < letter > | < identifier > < digit > < letter > =a|b|. . . |z|A|B|. . . |Z|_ < digit > =0|1|. . . |9 n Syntax graph Letter n Observations · · The definition is recursive Base case: · · 13 A letter ( length = 1) We need to construct a recognition algorithm Digit

Languages n Java Identifiers’ Recognition algorithm is. Id (in w: string): boolean // Returns

Languages n Java Identifiers’ Recognition algorithm is. Id (in w: string): boolean // Returns true if w is a legal Java identifier; // otherwise returns false. if (w is of length 1 ) // base case if (w is a letter) return true else return false else if (the last character of w is a letter or a digit) return is. Id (w minus its last character) else 14 return false // Point X

Palindromes n String that read the same from left-to-right as it does from right-to-left

Palindromes n String that read the same from left-to-right as it does from right-to-left n Examples RADAR Madam I’m Adam (without the blanks and quotes) n Language: Palindromes = { w : w reads the same from left to right n Grammar: as from right to left } <pal > = empty string | < ch > | a <pal > a |. . . | z <pal> z | A < pal > A |. . . | Z < pal > Z < ch > = a | b |. . . | z | A | B |. . . | Z n n · 15 The definition is recursive Base cases: · ? We need a recognition algorithm

Palindromes n Recognition algorithm is. Pal(in w: string) : boolean If (w is of

Palindromes n Recognition algorithm is. Pal(in w: string) : boolean If (w is of length 0 or 1) return true // Base-case success else if (first and last characters are the same) return Is. Pal( w minus first and last characters) else return false 16 // Base-case failure

An Bn Strings n Language: L = { w : w is of the

An Bn Strings n Language: L = { w : w is of the form An Bn for some n 0 } n Grammar: < legal n n The definition is recursive Base case: n 17 word > = empty string | A < legal word > B ?

An Bn Strings n Recognition algorithm Is. An. Bn(in w: string): boolean If (w

An Bn Strings n Recognition algorithm Is. An. Bn(in w: string): boolean If (w is of length 0) return true // Base–case success else if (w begins with ‘A’ & ends with ‘B’) return Is. An. Bn( w minus first & last characters) // Point A else return false // Base–case failure 18

Algebraic Expressions n Algebraic expression n A fully or partially parenthesized infix arithmetic expression

Algebraic Expressions n Algebraic expression n A fully or partially parenthesized infix arithmetic expression n Examples n n n Solution n 19 A+(B–C)*D { partially parenthesized} ( A + ( ( B – C ) * D )) {Fully parenthesized} Find a way to get rid of the parentheses completely

Algebraic Expressions n Infix expression: n n Binary operators appear between their operands Prefix

Algebraic Expressions n Infix expression: n n Binary operators appear between their operands Prefix (Polish) expression: n Binary operators appear before their operands n Postfix (Reverse Polish) expression: n Binary operators appear after their operands Examples: n Infix a+b a+(b*c) (a + b) * c 20 Prefix +ab +a*bc *+abc Postfix ab+ abc*+ ab+c*

Prefix Expressions n Language: L = { w : w is a prefix expression

Prefix Expressions n Language: L = { w : w is a prefix expression } n Grammar: < prefix > = <identifier> | < operator > < prefix 1> < prefix 2 > < operator > = + | - | * | / < identifier > = A | B |. . . | Z n n n Definition is recursive Size of prefix 1 & prefix 2 is smaller than prefix, since they are subexpressions Base case: n 21 When an identifier is reached

Prefix Expressions n How to Determine if a Given Expression is a Prefix Expression?

Prefix Expressions n How to Determine if a Given Expression is a Prefix Expression? 22

Prefix Expressions n How to Determine if a Given Expression is a Prefix Expression:

Prefix Expressions n How to Determine if a Given Expression is a Prefix Expression: 1. Construct a recursive valued function End-Pre (First, Last ) that returns either the index of the end of the prefix expression beginning at S(First), or -1 , if no such expression exists in the given string 2. Use the previous function to determine whether a character string S is a prefix expression 23

Prefix Expressions n End-Pre Function: (Tracing: Fig 6. 5, p. 309) end. Pre(first, last)

Prefix Expressions n End-Pre Function: (Tracing: Fig 6. 5, p. 309) end. Pre(first, last) // Finds the end of a prefix expression, if one exists. // If no such prefix expression exists, end. Pre should return – 1. if ((First < 0) or (First > Last)) // string is empty return – 1 ch = character at position first of str. Exp if (ch is an identifier) // index of last character in simple prefix expression return First else if (ch is an operator) { // find the end of the first prefix expression first. End = end. Pre(First+1, last) // Point X // if the end of the first expression was found // find the end of the second prefix expression if (first. End > -1) return end. Pre(first. End+1, last) // Point Y else return -1 } // end if else return -1 24

Prefix Expressions n Is. Pre Function n Uses end. Pre() to determine whether a

Prefix Expressions n Is. Pre Function n Uses end. Pre() to determine whether a string is a prefix or not Is. Pre(): boolean size= length of expression str. Exp last. Char = endpre(0, size-1) if (last. Char >= 0 and last. Char == str. Exp. length()-1) return true else return false 25

Prefix Expressions n Evaluate. Prefix Function n 26 E is the expression beginning at

Prefix Expressions n Evaluate. Prefix Function n 26 E is the expression beginning at Index evaluate. Prefix( str. Exp: string) // Evaluates a prefix expression str. Exp { Ch = first character of str. Exp Delete the first character from str. Exp if (Ch is an identifier) return value of the identifier else if (Ch is an operator named op) { Operand 1 = Evaluate. Prefix(str. Exp) Operand 2 = Evaluate. Prefix(str. Rxp) return Operand 1 op Operand 2 } // end if } // base case // Point A // Point B

Review n ______ is a problem-solving technique that involves guesses at a solution. n

Review n ______ is a problem-solving technique that involves guesses at a solution. n n 27 Recursion Backtracking Iteration Induction

Review n In the recursive solution to the Eight Queens problem, the problem size

Review n In the recursive solution to the Eight Queens problem, the problem size decreases by ______ at each recursive step. n n 28 one square two squares one column two columns

Review n A language is a set of strings of ______. n n 29

Review n A language is a set of strings of ______. n n 29 numbers letters Alphabets symbols

Review The statement: Java. Programs = {strings w : w is a syntactically n

Review The statement: Java. Programs = {strings w : w is a syntactically n correct Java program} signifies that ______. n n 30 all strings are syntactically correct Java programs all syntactically correct Java programs are strings the Java. Programs language consists of all the possible strings a string is a language

Review n The Java ______ determines whether a given string is a syntactically correct

Review n The Java ______ determines whether a given string is a syntactically correct Java program. n n 31 applet editor compiler programmer

Review n If the string w is a palindrome, which of the following is

Review n If the string w is a palindrome, which of the following is true? n n n 32 w minus its first character is a palindrome w minus its last character is a palindrome w minus its first and last characters is a palindrome the first half of w is a palindrome the second half of w is a palindrome

Review n Which of the following strings is a palindrome? n n 33 “bottle”

Review n Which of the following strings is a palindrome? n n 33 “bottle” “beep” “coco” “r

Review n The symbol An. Bn is standard notation for the string that consists

Review n The symbol An. Bn is standard notation for the string that consists of ______. n n 34 an A, followed by an n, followed by a B, followed by an n an equal number of A’s and B’s, arranged in a random order n consecutive A’s, followed by n consecutive B’s a pair of an A and a B, followed another pair of an A and a B

Review n Which of the following is an infix expression? n n 35 /a+bc

Review n Which of the following is an infix expression? n n 35 /a+bc abc+/ ab/+c a / (b + c)

Review n What is the value of the prefix expression: – * 3 8

Review n What is the value of the prefix expression: – * 3 8 + 6 5? n n 36 11 23 13 21