Presentation is loading. Please wait.

Presentation is loading. Please wait.

COSC2007 Data Structures II

Similar presentations


Presentation on theme: "COSC2007 Data Structures II"— Presentation transcript:

1 COSC2007 Data Structures II
April 23, 2017 COSC Data Structures II Chapter 6 Recursion as a Problem-Solving Technique Recursion as a Problem-Solving Technique

2 Topics 8-Queen problem Languages Algebraic expressions
April 23, 2017 Topics 8-Queen problem Languages Algebraic expressions Prefix & Postfix notation & conversion Recursion as a Problem-Solving Technique

3 Introduction Backtracking:
April 23, 2017 Introduction Backtracking: 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 Tic-Tac-Toe Recursion as a Problem-Solving Technique

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

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

6 Eight-Queens Problem Solution Idea:
April 23, 2017 Eight-Queens Problem Solution Idea: 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 Recursion as a Problem-Solving Technique

7 April 23, 2017 Eight-Queens Problem How can we use recursion for solving this problem? For placing a queen in a column, assuming that previous queens were placed correctly 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 Base case: Either we reach a solution to the problem with no columns left  Success & finish Or all previous queens will be under attack  Failure & Backtrack Recursion as a Problem-Solving Technique

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

9 Eight-Queens Problem Implementation: Classes: Data members QueenClass
April 23, 2017 Eight-Queens Problem Implementation: Classes: QueenClass Data members board: How? square Indicates that the square has a queen or is empty Recursion as a Problem-Solving Technique

10 Eight-Queens Problem Textbook provides partial implementation
April 23, 2017 Eight-Queens Problem Implementation: Methods needed: Public functions (methods) ClearBoard: Sets all squares to empty DisplayBoard: Displays the board PlaceQueens: Places the queens in board’s columns & returns either success or failure Private functions (methods) SetQueen: Sets a given square to QUEEN RemoveQueen: Sets a given square to EMPTY IsUnderAttack: Checks if a given square is under attack Index: Returns the array index corresponding to a row or column Textbook provides partial implementation Recursion as a Problem-Solving Technique

11 Languages Language: A set of strings of symbols
April 23, 2017 Languages Language: A set of strings of symbols Can be described using syntax rules Examples: Java program program = { w : w is a syntactically correct java program} Algebraic expressions Algebraic Expression = { w : w is an algebraic expression } Recursion as a Problem-Solving Technique

12 Languages Language recognizer: Recognition algorithm:
April 23, 2017 Languages Language recognizer: A program (or machine) that accepts a sentence and determines whether the sentence belongs to the language Recognition algorithm: 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 Recursion as a Problem-Solving Technique

13 Languages Example: Grammar for Java identifiers Grammar Syntax graph
April 23, 2017 Languages Example: Grammar for Java identifiers Java Ids = {w:w is a legal Java identifier} Grammar < identifier > = < letter > | < identifier > < letter > | < identifier > < digit > < letter > = a | b | | z | A | B | | Z | _ < digit > = 0 | 1 | | 9 Syntax graph Observations The definition is recursive Base case: A letter ( length = 1) We need to construct a recognition algorithm Letter Digit Recursion as a Problem-Solving Technique

14 Languages Java Identifiers’ Recognition algorithm
April 23, 2017 Languages Java Identifiers’ Recognition algorithm isId (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 isId (w minus its last character) // Point X Recursion as a Problem-Solving Technique

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

16 Palindromes Recognition algorithm isPal(in w: string) : boolean
April 23, 2017 Palindromes Recognition algorithm isPal(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 IsPal( w minus first and last characters) return false // Base-case failure Recursion as a Problem-Solving Technique

17 An Bn Strings Language: Grammar: The definition is recursive
April 23, 2017 An Bn Strings Language: L = { w : w is of the form An Bn for some n  0 } Grammar: < legal word > = empty string | A < legal word > B The definition is recursive Base case: ? Recursion as a Problem-Solving Technique

18 An Bn Strings Recognition algorithm IsAnBn(in w: string): boolean
April 23, 2017 An Bn Strings Recognition algorithm IsAnBn(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 IsAnBn( w minus first & last characters) // Point A else return false // Base–case failure Recursion as a Problem-Solving Technique

19 Algebraic Expressions
April 23, 2017 Algebraic Expressions Algebraic expression A fully or partially parenthesized infix arithmetic expression Examples A + ( B – C ) * D { partially parenthesized} ( A + ( ( B – C ) * D )) {Fully parenthesized} Solution Find a way to get rid of the parentheses completely Recursion as a Problem-Solving Technique

20 Algebraic Expressions
April 23, 2017 Algebraic Expressions Infix expression: Binary operators appear between their operands Prefix (Polish) expression: Binary operators appear before their operands Postfix (Reverse Polish) expression: Binary operators appear after their operands Examples: Infix Prefix Postfix a + b + a b a b + a + ( b * c ) a * b c a b c * + (a + b) * c * + a b c a b + c * Recursion as a Problem-Solving Technique

21 Prefix Expressions Language: Grammar: Definition is recursive
April 23, 2017 Prefix Expressions Language: L = { w : w is a prefix expression } Grammar: < prefix > = <identifier> | < operator > < prefix1> < prefix2 > < operator > = + | - | * | / < identifier > = A | B | | Z Definition is recursive Size of prefix1 & prefix2 is smaller than prefix, since they are subexpressions Base case: When an identifier is reached Recursion as a Problem-Solving Technique

22 April 23, 2017 Prefix Expressions How to Determine if a Given Expression is a Prefix Expression? Recursion as a Problem-Solving Technique

23 April 23, 2017 Prefix Expressions 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 Recursion as a Problem-Solving Technique

24 Prefix Expressions End-Pre Function: (Tracing: Fig 6.5, p.309)
April 23, 2017 Prefix Expressions End-Pre Function: (Tracing: Fig 6.5, p.309) endPre(first, last) // Finds the end of a prefix expression, if one exists. // If no such prefix expression exists, endPre should return –1. if ((First < 0) or (First > Last)) // string is empty return –1 ch = character at position first of strExp 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 firstEnd = endPre(First+1, last) // Point X // if the end of the first expression was found // find the end of the second prefix expression if (firstEnd > -1) return endPre(firstEnd+1, last) // Point Y else return -1 } // end if Recursion as a Problem-Solving Technique

25 Prefix Expressions IsPre Function IsPre(): boolean
April 23, 2017 Prefix Expressions IsPre Function Uses endPre() to determine whether a string is a prefix or not IsPre(): boolean size= length of expression strExp lastChar = endpre(0, size-1) if (lastChar >= 0 and lastChar == strExp.length()-1) return true else return false Recursion as a Problem-Solving Technique

26 Prefix Expressions EvaluatePrefix Function
April 23, 2017 Prefix Expressions EvaluatePrefix Function E is the expression beginning at Index evaluatePrefix( strExp: string) // Evaluates a prefix expression strExp { Ch = first character of strExp Delete the first character from strExp if (Ch is an identifier) return value of the identifier // base case else if (Ch is an operator named op) { Operand1 = EvaluatePrefix(strExp) // Point A Operand2 = EvaluatePrefix(strRxp) // Point B return Operand1 op Operand2 } // end if } Recursion as a Problem-Solving Technique

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

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

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

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

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

32 Review If the string w is a palindrome, which of the following is true? 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

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

34 Review The symbol AnBn is standard notation for the string that consists of ______. 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

35 Review Which of the following is an infix expression? / a + b c

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


Download ppt "COSC2007 Data Structures II"

Similar presentations


Ads by Google