Backtracking. Module 6. The Eight Queens Problem. CS 147 Sam Houston State University Dr. McGuire. Backtracking. Recursion Revisited

Similar documents
Backtracking. The Eight Queens Problem. The Eight Queens Problem. The Eight Queens Problem. The Eight Queens Problem. Chapter 5

8/22/12. Outline. Backtracking. The Eight Queens Problem. Backtracking. Part 1. Recursion as a Problem-Solving Technique

Recursion Solution. Counting Things. Searching an Array. Organizing Data. Backtracking. Defining Languages

Recursion as a Problem-Solving Technique. Chapter 5

Lecture Chapter 6 Recursion as a Problem Solving Technique

CS200: Recursion and induction (recap from cs161)

STACKS. A stack is defined in terms of its behavior. The common operations associated with a stack are as follows:

This book is licensed under a Creative Commons Attribution 3.0 License

A Simple Syntax-Directed Translator

Stacks. Chapter 5. Copyright 2012 by Pearson Education, Inc. All rights reserved

CS 171: Introduction to Computer Science II. Stacks. Li Xiong

SEQUENCES, MATHEMATICAL INDUCTION, AND RECURSION

09 STACK APPLICATION DATA STRUCTURES AND ALGORITHMS REVERSE POLISH NOTATION

March 13/2003 Jayakanth Srinivasan,

Examples of attributes: values of evaluated subtrees, type information, source file coordinates,

Inference rule for Induction

COMP-421 Compiler Design. Presented by Dr Ioanna Dionysiou

Stacks. stacks of dishes or trays in a cafeteria. Last In First Out discipline (LIFO)

Tutorial 3: Infix, Prefix, Postfix & Tower of Hanoi

Recursion defining an object (or function, algorithm, etc.) in terms of itself. Recursion can be used to define sequences

CmpSci 187: Programming with Data Structures Spring 2015

CMSC 132: Object-Oriented Programming II. Recursive Algorithms. Department of Computer Science University of Maryland, College Park

Recursive definition of sets and structural induction

Principles of Programming Languages COMP251: Syntax and Grammars

Stacks CS102 Sections 51 and 52 Marc Smith and Jim Ten Eyck Spring 2008

Intro to semantics; Small-step semantics Lecture 1 Tuesday, January 29, 2013

Linear Data Structure

EC8393FUNDAMENTALS OF DATA STRUCTURES IN C Unit 3

Operators. Java operators are classified into three categories:

- Wikipedia Commons. Intro Problem Solving in Computer Science 2011 McQuain

CS W3134: Data Structures in Java

Stack Applications. Lecture 27 Sections Robb T. Koether. Hampden-Sydney College. Wed, Mar 29, 2017

Introduction. Problem Solving on Computer. Data Structures (collection of data and relationships) Algorithms

Recursive Methods and Problem Solving. Chris Kiekintveld CS 2401 (Fall 2010) Elementary Data Structures and Algorithms

UNIT I Programming Language Syntax and semantics. Kainjan Sanghavi

Some Applications of Stack. Spring Semester 2007 Programming and Data Structure 1

DATA ABSTRACTION AND PROBLEM SOLVING WITH JAVA

Chapter 3: CONTEXT-FREE GRAMMARS AND PARSING Part 1

More Assigned Reading and Exercises on Syntax (for Exam 2)

Introduction to Automata Theory. BİL405 - Automata Theory and Formal Languages 1

Defining Binary & Unary Operators

Discrete Structures. Fall Homework3

Stack Applications. Lecture 25 Sections Robb T. Koether. Hampden-Sydney College. Mon, Mar 30, 2015

DEEPIKA KAMBOJ UNIT 2. What is Stack?

n Data structures that reflect a temporal relationship q order of removal based on order of insertion n We will consider:

Stack Abstract Data Type

Stacks (Section 2) By: Pramod Parajuli, Department of Computer Science, St. Xavier s College, Nepal.

Recursion defining an object (or function, algorithm, etc.) in terms of itself. Recursion can be used to define sequences

PA3 Design Specification

Warmup Problem. Translate the following sentence from English into Propositional Logic. I want to eat ice cream even though I am on a diet.

Chapter 3: Describing Syntax and Semantics. Introduction Formal methods of describing syntax (BNF)

Test Bank Ver. 5.0: Data Abstraction and Problem Solving with C++: Walls and Mirrors, 5 th edition, Frank M. Carrano

Defining! Binary & Unary! Operators!

Introduction p. 1 Pseudocode p. 2 Algorithm Header p. 2 Purpose, Conditions, and Return p. 3 Statement Numbers p. 4 Variables p. 4 Algorithm Analysis

CMPSCI 187: Programming With Data Structures. Lecture #15: Thinking Recursively David Mix Barrington 10 October 2012

Stacks. Access to other items in the stack is not allowed A LIFO (Last In First Out) data structure

infix expressions (review)

Defining Binary & Unary Operators DO-1

2.2 Syntax Definition

Recursive Definitions

Stating the obvious, people and computers do not speak the same language.

Stacks Calculator Application. Alexandra Stefan

LECTURE 17. Expressions and Assignment

Formal Languages and Automata Theory, SS Project (due Week 14)

Sir Muhammad Naveed. Arslan Ahmed Shaad ( ) Muhammad Bilal ( )

Data Structures. Chapter 06. 3/10/2016 Md. Golam Moazzam, Dept. of CSE, JU

Recursion. Recursion is: Recursion splits a problem:

IPCoreL. Phillip Duane Douglas, Jr. 11/3/2010

Recursion. EECS2030: Advanced Object Oriented Programming Fall 2017 CHEN-WEI WANG

CSE 12 Abstract Syntax Trees

Supplemental Materials: Grammars, Parsing, and Expressions. Topics. Grammars 10/11/2017. CS2: Data Structures and Algorithms Colorado State University

SECTION 5.1. Sequences

Stacks, Queues and Hierarchical Collections. 2501ICT Logan

CMPT 225. Stacks-part2

Functional Programming. Pure Functional Programming

Specifying Syntax. An English Grammar. Components of a Grammar. Language Specification. Types of Grammars. 1. Terminal symbols or terminals, Σ

Recursion. Tracing Method Calls via a Stack. Beyond this lecture...

Stacks. Revised based on textbook author s notes.

CS302 Data Structures using C++

CSE au Final Exam Sample Solution

Recursion: Factorial (1) Recursion. Recursion: Principle. Recursion: Factorial (2) Recall the formal definition of calculating the n factorial:

GE PROBLEM SOVING AND PYTHON PROGRAMMING. Question Bank UNIT 1 - ALGORITHMIC PROBLEM SOLVING

Lexical Analysis. COMP 524, Spring 2014 Bryan Ward

Assessment of Programming Skills of First Year CS Students: Problem Set

Recursive Definitions Structural Induction Recursive Algorithms

STACKS AND QUEUES. Problem Solving with Computers-II

G Programming Languages - Fall 2012

Induction and Recursion. CMPS/MATH 2170: Discrete Mathematics

Section Summary. Introduction to Trees Rooted Trees Trees as Models Properties of Trees

ITEC2620 Introduction to Data Structures


12 Abstract Data Types

Lexical Analysis. Lexical analysis is the first phase of compilation: The file is converted from ASCII to tokens. It must be fast!

SimpleCalc. which can be entered into a TI calculator, like the one on the right, like this:

EE 368. Weeks 4 (Notes)

Lecture 4: Stack Applications CS2504/CS4092 Algorithms and Linear Data Structures. Parentheses and Mathematical Expressions

Stack. 4. In Stack all Operations such as Insertion and Deletion are permitted at only one end. Size of the Stack 6. Maximum Value of Stack Top 5

APCS-AB: Java. Recursion in Java December 12, week14 1

SCHEME 8. 1 Introduction. 2 Primitives COMPUTER SCIENCE 61A. March 23, 2017

Stacks, Queues and Hierarchical Collections

Transcription:

Module 6 Recursion Revisited CS 147 Sam Houston State University Dr. McGuire Backtracking Backtracking A strategy for guessing at a solution and backing up when an impasse is reached Recursion and backtracking can be combined to solve problems 2007 Timothy J. McGuire, Ph.D. 6-1 2007 Timothy J. McGuire, Ph.D. 6-2 Problem Place eight queens on the chessboard so that no queen can attack any other queen Strategy: guess at a solution There are 4,426,165,368 ways to arrange 8 queens on a chessboard of 64 squares An observation that eliminates many arrangements from consideration No queen can reside in a row or a column that contains another queen Now: only 40,320 arrangements of queens to be checked for attacks along diagonals 2007 Timothy J. McGuire, Ph.D. 6-3 2007 Timothy J. McGuire, Ph.D. 6-4 Providing organization for the guessing strategy Place queens one column at a time If you reach an impasse, backtrack to the previous column a) Five queens that cannot attack each other, but that can attack all of column 6; b) backtracking to column 5 to try another square for the queen; c) backtracking to column 4 to try another square for the queen and then considering column 5 again 2007 Timothy J. McGuire, Ph.D. 6-5 2007 Timothy J. McGuire, Ph.D. 6-6 1

A recursive algorithm that places a queen in a column Base case If there are no more columns to consider You are finished Recursive step If you successfully place a queen in the current column Consider the next column If you cannot place a queen in the current column You need to backtrack A solution to the Eight Queens problem 2007 Timothy J. McGuire, Ph.D. 6-7 2007 Timothy J. McGuire, Ph.D. 6-8 Defining Languages Defining Languages A language A set of strings of symbols Examples: English, Java If a Java program is one long string of characters, the language JavaPrograms is defined as JavaPrograms = {strings w : w is a syntactically correct Java program A language does not have to be a programming or a communication language Example The set of algebraic expressions AlgebraicExpressions = {w : w is an algebraic expression 2007 Timothy J. McGuire, Ph.D. 6-9 2007 Timothy J. McGuire, Ph.D. 6-10 Defining Languages The Basics of Grammars States the rules for forming the strings in a language Benefit of recursive grammars Ease of writing a recognition algorithm for the language A recognition algorithm determines whether a given string is in the language Symbols used in grammars x y means x or y x y means x followed by y (In x y, the symbol means concatenate, or append) < word > means any instance of word that the definition defines 2007 Timothy J. McGuire, Ph.D. 6-11 2007 Timothy J. McGuire, Ph.D. 6-12 2

The Basics of Grammars The Basics of Grammars Java identifiers A Java identifier begins with a letter and is followed by zero or more letters and digits Java identifiers Language JavaIds = {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 A syntax diagram for Java identifiers 2007 Timothy J. McGuire, Ph.D. 6-13 2007 Timothy J. McGuire, Ph.D. 6-14 The Basics of Grammars Two Simple Languages: Palindromes Recognition algorithm isid(w) if (w is of length 1) { if (w is a letter) { else if (the last character of w is a letter or a digit) { return isid(w minus its last character) A string that reads the same from left to right as it does from right to left Examples: radar, deed Language Plid Palindromes = {w : w reads the same left lftto right ihtas right to left 2007 Timothy J. McGuire, Ph.D. 6-15 2007 Timothy J. McGuire, Ph.D. 6-16 Palindromes Palindromes < pal > = empty string < ch > a < pal > a b < pal > b Z < pal > Z < ch > = a b z A B Z Recognition algorithm ispal(w) if (w is the empty string or w is of length 1) { else if (w s first and last characters are the same letter ) { return ispal(w minus its first and last characters) 2007 Timothy J. McGuire, Ph.D. 6-17 2007 Timothy J. McGuire, Ph.D. 6-18 3

Strings of the form A n B n A n B n The string that consists of n consecutive A s followed by n consecutive B s Language L = {w : w is of the form A n B n for some n 0 < legal word > = empty string A < legal word > B Strings of the form A n B n Recognition algorithm isanbn(w) if (the length of w is zero) { else if (w begins with the character A and ends with the character B) { return isanbn(w minus its first and last characters) 2007 Timothy J. McGuire, Ph.D. 6-19 2007 Timothy J. McGuire, Ph.D. 6-20 Three languages for algebraic expressions Infix expressions An operator appears between its operands Example: a + b Prefix expressions An operator appears before its operands Example: + a b Postfix expressions An operator appears after its operands Example: a b + To convert a fully parenthesized infix expression to a prefix form Move each operator to the position marked by its corresponding open parenthesis Remove the parentheses Example Infix expression: ((a + b) * c Prefix expression: * + a b c 2007 Timothy J. McGuire, Ph.D. 6-21 2007 Timothy J. McGuire, Ph.D. 6-22 To convert a fully parenthesized infix expression to a postfix form Move each operator to the position marked by its corresponding closing parenthesis Remove the parentheses Example Infix form: ((a + b) * c) Postfix form: a b + c * Prefix and postfix expressions Never need Precedence rules Association rules Parentheses Have Simple grammar expressions Straightforward recognition and evaluation algorithms 2007 Timothy J. McGuire, Ph.D. 6-23 2007 Timothy J. McGuire, Ph.D. 6-24 4

Prefix Expressions < prefix > = < identifier > < operator > < prefix > < prefix > < operator > = + * / < identifier > = a b z A recognition algorithm ispre() size = length of expression strexp lastchar = endpre(0, size 1) if (lastchar >= 0 and lastchar == size-1 { Prefix Expressions An algorithm that evaluates a prefix expression evaluateprefix(strexp) ch = first character of expression strexp Delete first character from strexp if (ch is an identifier) { return value of the identifier else if (ch is an operator named op) { operand1 = evaluateprefix(strexp) operand2 = evaluateprefix(strexp) return operand1 op operand2 2007 Timothy J. McGuire, Ph.D. 6-25 2007 Timothy J. McGuire, Ph.D. 6-26 Postfix Expressions < postfix > = < identifier > < postfix > < postfix > < operator> < operator > = + * / < identifier > = a b z At high level, an algorithm that converts a prefix expression to postfix form if (exp is a single letter) { return exp return postfix(prefix1) + postfix(prefix2) + operator Postfix Expressions A recursive algorithm that converts a prefix expression to postfix form convert(pre) ch = first character of pre Delete first character of pre if (ch is a lowercase letter) { return ch as a string postfix1 = convert(pre) postfix2 = convert(pre) return postfix1 + postfix2 + ch 2007 Timothy J. McGuire, Ph.D. 6-27 2007 Timothy J. McGuire, Ph.D. 6-28 Fully Parenthesized Expressions To avoid ambiguity, infix notation normally requires Precedence rules Rules for association Parentheses Fullyparenthesizedexpressions expressions donotrequire Precedence rules Rules for association Fully Parenthesized Expressions Fully parenthesized expressions A simple grammar < infix > = < identifier > (< infix > < operator > < infix > ) < operator > = + * / < identifier > = a b z Inconvenient for programmers 2007 Timothy J. McGuire, Ph.D. 6-29 2007 Timothy J. McGuire, Ph.D. 6-30 5

The Relationship Between Recursion and Mathematical Induction A strong relationship exists between recursion and mathematical induction Induction can be used to Prove properties about recursive algorithms Prove that a recursive algorithm performs a certain amount of work The Correctness of the Recursive Factorial Method Pseudocode for a recursive method that computes the factorial of a nonnegative integer n fact(n) if (n is 0) { return 1 return n * fact(n 1) 2007 Timothy J. McGuire, Ph.D. 6-31 2007 Timothy J. McGuire, Ph.D. 6-32 The Correctness of the Recursive Factorial Method Induction on n can prove that the method fact returns the values fact(0) = 0! = 1 fact(n) = n! = n * (n 1) * (n 2) * * 1 if n > 0 The Cost of Towers of Hanoi Solution to the Towers of Hanoi problem solvetowers(count, source, destination, spare) if (count is 1) { Move a disk directly from source to destination solvetowers(count-1, source, spare, destination) solvetowers(1, source, destination, spare) solvetowers(count-1, spare, destination, source) 2007 Timothy J. McGuire, Ph.D. 6-33 2007 Timothy J. McGuire, Ph.D. 6-34 The Cost of Towers of Hanoi The Cost of Towers of Hanoi Question If you begin with N disks, how many moves does solvetowers make to solve the problem? Let moves(n) be the number of moves made starting with N disks When N = 1 moves(1) = 1 When N > 1 moves(n) = moves(n 1) + moves(1) + moves(n 1) Recurrence relation for the number of moves that solvetowers requires for N disks moves(1) = 1 moves(n) = 2 * moves(n 1) + 1 if N > 1 2007 Timothy J. McGuire, Ph.D. 6-35 2007 Timothy J. McGuire, Ph.D. 6-36 6

The Cost of Towers of Hanoi Summary A closed form formula for the number of moves that solvetowers requires for N disks moves(n) = 2 N 1, for all N 1 Induction on N can provide the proof that moves(n) = 2 N 1 Backtracking is a solution strategy that involves both recursion and a sequence of guesses that ultimately lead to a solution A grammar is a device for defining a language A language is a set of strings of symbols A recognition algorithm for a language can often be based directly on the grammar of the language Grammars are frequently recursive 2007 Timothy J. McGuire, Ph.D. 6-37 2007 Timothy J. McGuire, Ph.D. 6-38 Summary Different languages of algebraic expressions have their relative advantages and disadvantages Prefix expressions Postfix expressions Infix expressions A close relationship exists between mathematical induction and recursion Induction can be used to prove properties about a recursive algorithm 2007 Timothy J. McGuire, Ph.D. 6-39 7