CSE 143 Lecture 17 Recursive Backtracking

Slides:



Advertisements
Similar presentations
COSC2007 Data Structures II
Advertisements

Announcements Assignment #4 is due tonight. Last lab program is going to be assigned this Wednesday. ◦ A backtracking problem.
Building Java Programs
CSE 143 Lecture 18 Binary Trees read slides created by Marty Stepp and Hélène Martin
Backtracking COP Backtracking  Backtracking is a technique used to solve problems with a large search space, by systematically trying and eliminating.
Backtracking What is backtracking?
Building Java Programs
Building Java Programs Chapter 12 Recursion Copyright (c) Pearson All rights reserved.
Recursion: Backtracking
CSE 143 Lecture 17 More Recursive Backtracking reading: "Appendix R" on course web site slides created by Marty Stepp and Hélène Martin
CSE 143 Lecture 17 More Recursive Backtracking reading: "Appendix R" on course web site slides created by Marty Stepp and Hélène Martin
CSC 205 Programming II Lecture 18 The Eight Queens Problem.
Data Structures Using C++ 2E1 Recursion and Backtracking: DFS Depth first search (a way to traverse a tree or graph) Backtracking can be regarded as a.
CSE 143 Lecture 18 Recursive Backtracking reading: 12.5 or "Appendix R" on course web site slides adapted from Marty Stepp and Hélène Martin
Building Java Programs Appendix R Recursive backtracking.
1 Data Structures CSCI 132, Spring 2014 Lecture 17 Backtracking.
The "8 Queens" problem Consider the problem of trying to place 8 queens on a chess board such that no queen can attack another queen. What are the "choices"?
CSE 143 Lecture 18 More Recursive Backtracking slides created by Marty Stepp
CSE 143 Lecture 13 Recursive Backtracking slides created by Ethan Apter
Analysis & Design of Algorithms (CSCE 321)
Contest Algorithms January 2016 Pseudo-code for backtracking search, and three examples (all subsets, permutations, and 8- queens). 4. Backtracking 1Contest.
CompSci Problem Solving: Sudoku  Rules of the Game Sudoku is played with a 9 by 9 "board" consisting of nine 3 by 3 sub-boards. The symbols 1 -
Recursion Copyright (c) Pearson All rights reserved.
Recursion. 2 recursion: The definition of an operation in terms of itself. –Solving a problem using recursion depends on solving smaller occurrences of.
CSE 143 Lecture 17 Recursive Backtracking slides created by Marty Stepp ideas and examples taken from Stanford University.
CSE 143 read: 12.5 Lecture 18: recursive backtracking.
1 Tirgul 11: Recursion & Backtracking. 2 Elements of a recursive solution (Reminder) A base case that is so simple we need no computation to solve it.
CSG3F3/ Desain dan Analisis Algoritma
Recursion Data Structure Submitted By:- Dheeraj Kataria.
Backtracking, Search, Heuristics
Depth-First Search N-Queens Problem Hamiltonian Circuits
CSSE 230 Day 25 Skip Lists.
Intro to Computer Science II
CSCI 104 Backtracking Search
Data Structures and Algorithms
read: 12.5 Lecture 17: recursive backtracking
The "8 Queens" problem Consider the problem of trying to place 8 queens on a chess board such that no queen can attack another queen. What are the "choices"?
CSE 143 Lecture 19 More Recursive Backtracking
1) RECURSION 2) BACKTRACKING 3) LOOK AHEAD
Using a Stack Chapter 6 introduces the stack data type.
Algorithm Design and Analysis (ADA)
Building Java Programs
Recursion Copyright (c) Pearson All rights reserved.
CSCI 162 – Introduction to Programming II Prof. William Killian
Analysis and design of algorithm
Using a Stack Chapter 6 introduces the stack data type.
Exercise: fourAB Write a method fourAB that prints out all strings of length 4 composed only of a’s and b’s Example Output aaaa baaa aaab baab aaba baba.
CSS 342 Data Structures, Algorithms, and Discrete Mathematics I
Exercise: Dice roll sum
Recursive Backtracking Based on slides by Marty Stepp & Ethan Apter
Road Map - Quarter CS Concepts Data Structures Java Language
adapted from Recursive Backtracking by Mike Scott, UT Austin
CSE 143 Lecture 17 Recursive Backtracking
CSE 143 Lecture 15 Recursive Backtracking
Exercise: Dice roll sum Write a method diceSum similar to diceRoll, but it also accepts a desired sum and prints only arrangements that add up to.
Exercise: Dice roll sum
Recursion James Brucker.
Algorithms: Design and Analysis
Road Map - Quarter CS Concepts Data Structures Java Language
CSE 143 Lecture 18 More Recursive Backtracking
Recursive backtracking
Exercise: Dice rolls Write a method diceRoll that accepts an integer parameter representing a number of 6-sided dice to roll, and output all possible arrangements.
CSE 143 Lecture 18 More Recursive Backtracking
Exercise: Dice roll sum
Recursive backtracking
The "8 Queens" problem Consider the problem of trying to place 8 queens on a chess board such that no queen can attack another queen. What are the "choices"?
CSE 143 Lecture 12 Recursive Backtracking
Backtracking, Search, Heuristics
Announcements Assignment #4 is due tonight. Last lab program is going to be assigned this Wednesday. ◦ A backtracking problem.
Backtracking, Search, Heuristics
Presentation transcript:

CSE 143 Lecture 17 Recursive Backtracking slides created by Marty Stepp http://www.cs.washington.edu/143/

Exercise Write a method permute that accepts a string as a parameter and outputs all possible rearrangements of the letters in that string. The arrangements may be output in any order. Example: permute("MARTY") outputs the following sequence of lines: MARTY MARYT MATRY MATYR MAYRT MAYTR MRATY MRAYT MRTAY MRTYA MRYAT MRYTA MTARY MTAYR MTRAY MTRYA MTYAR MTYRA MYART MYATR MYRAT MYRTA MYTAR MYTRA AMRTY AMRYT AMTRY AMTYR AMYRT AMYTR ARMTY ARMYT ARTMY ARTYM ARYMT ARYTM ATMRY ATMYR ATRMY ATRYM ATYMR ATYRM AYMRT AYMTR AYRMT AYRTM AYTMR AYTRM RMATY RMAYT RMTAY RMTYA RMYAT RMYTA RAMTY RAMYT RATMY RATYM RAYMT RAYTM RTMAY RTMYA RTAMY RTAYM RTYMA RTYAM RYMAT RYMTA RYAMT RYATM RYTMA RYTAM TMARY TMAYR TMRAY TMRYA TMYAR TMYRA TAMRY TAMYR TARMY TARYM TAYMR TAYRM TRMAY TRMYA TRAMY TRAYM TRYMA TRYAM TYMAR TYMRA TYAMR TYARM TYRMA TYRAM YMART YMATR YMRAT YMRTA YMTAR YMTRA YAMRT YAMTR YARMT YARTM YATMR YATRM YRMAT YRMTA YRAMT YRATM YRTMA YRTAM YTMAR YTMRA YTAMR YTARM YTRMA YTRAM interesting variation: Output only the *unique* rearrangements. For example, permute("GOOGLE") has two Os, but swapping them in order produces the same string, which shouldn't appear twice in the output.

Examining the problem Think of each permutation as a set of choices or decisions: Which character do I want to place first? Which character do I want to place second? ... solution space: set of all possible sets of decisions to explore We want to generate all possible sequences of decisions. for (each possible first letter): for (each possible second letter): for (each possible third letter): print! This is called a depth-first search

Decision trees chosen available M A R T Y M A R T Y A M R T Y ... M A A T Y M T A R Y M Y A R T ... ... ... M A R T Y M A T R Y M A Y R T M Y A R T ... ... M A R T Y M A R Y T M A Y R T M A Y T R M A R T Y M A R Y T M A Y R T M A Y T R

Backtracking backtracking: A general algorithm for finding solution(s) to a computational problem by trying partial solutions and then abandoning them ("backtracking") if they are not suitable. a "brute force" algorithmic technique (tries all paths; not clever) often (but not always) implemented recursively Applications: producing all permutations of a set of values parsing languages games: anagrams, crosswords, word jumbles, 8 queens combinatorics and logic programming

Backtracking algorithms A general pseudo-code algorithm for backtracking problems: explore(choices): if there are no more choices to make: stop. else: Make a single choice C from the set of choices. Remove C from the set of choices. explore the remaining choices. Un-make choice C. Backtrack!

Backtracking strategies When solving a backtracking problem, ask these questions: What are the "choices" in this problem? What is the "base case"? (How do I know when I'm out of choices?) How do I "make" a choice? Do I need to create additional variables to remember my choices? Do I need to modify the values of existing variables? How do I explore the rest of the choices? Do I need to remove the made choice from the list of choices? Once I'm done exploring the rest, what should I do? How do I "un-make" a choice?

Permutations revisited Write a method permute that accepts a string as a parameter and outputs all possible rearrangements of the letters in that string. The arrangements may be output in any order. Example: permute("MARTY") outputs the following sequence of lines: MARTY MARYT MATRY MATYR MAYRT MAYTR MRATY MRAYT MRTAY MRTYA MRYAT MRYTA MTARY MTAYR MTRAY MTRYA MTYAR MTYRA MYART MYATR MYRAT MYRTA MYTAR MYTRA AMRTY AMRYT AMTRY AMTYR AMYRT AMYTR ARMTY ARMYT ARTMY ARTYM ARYMT ARYTM ATMRY ATMYR ATRMY ATRYM ATYMR ATYRM AYMRT AYMTR AYRMT AYRTM AYTMR AYTRM RMATY RMAYT RMTAY RMTYA RMYAT RMYTA RAMTY RAMYT RATMY RATYM RAYMT RAYTM RTMAY RTMYA RTAMY RTAYM RTYMA RTYAM RYMAT RYMTA RYAMT RYATM RYTMA RYTAM TMARY TMAYR TMRAY TMRYA TMYAR TMYRA TAMRY TAMYR TARMY TARYM TAYMR TAYRM TRMAY TRMYA TRAMY TRAYM TRYMA TRYAM TYMAR TYMRA TYAMR TYARM TYRMA TYRAM YMART YMATR YMRAT YMRTA YMTAR YMTRA YAMRT YAMTR YARMT YARTM YATMR YATRM YRMAT YRMTA YRAMT YRATM YRTMA YRTAM YTMAR YTMRA YTAMR YTARM YTRMA YTRAM interesting variation: Output only the *unique* rearrangements. For example, permute("GOOGLE") has two Os, but swapping them in order produces the same string, which shouldn't appear twice in the output.

Exercise solution // Outputs all permutations of the given string. public static void permute(String s) { permute(s, ""); } private static void permute(String s, String s2) { if (s.length() == 0) { // base case: no choices left to be made System.out.println(s2); } else { // recursive case: choose each possible next letter for (int i = 0; i < s.length(); i++) { String ch = s.substring(i, i + 1); // choose String rest = s.substring(0, i) + // remove s.substring(i + 1); permute(rest, s2 + ch); // explore

The "8 Queens" problem Consider the problem of trying to place 8 queens on a chess board such that no queen can attack another queen. What are the "choices"? How do we "make" or "un-make" a choice? How do we know when to stop? Q

Naive algorithm for (each square on the board): Place a queen there. Try to place the rest of the queens. Un-place the queen. How large is the solution space for this algorithm? 64 * 63 * 62 * ... 1 2 3 4 5 6 7 8 Q ...

Better algorithm idea Observation: In a working solution, exactly 1 queen must appear in each row and in each column. Redefine a "choice" to be valid placement of a queen in a particular column. How large is the solution space now? 8 * 8 * 8 * ... 1 2 3 4 5 6 7 8 Q ...

Exercise Suppose we have a Board class with the following methods: Write a method solveQueens that accepts a Board as a parameter and tries to place 8 queens on it safely. Your method should stop exploring if it finds a solution. Method/Constructor Description public Board(int size) construct empty board public boolean isSafe(int row, int column) true if queen can be safely placed here public void place(int row, int column) place queen here public void remove(int row, int column) remove queen from here public String toString() text display of board

Exercise solution // Searches for a solution to the 8 queens problem // with this board, reporting the first result found. public static void solveQueens(Board board) { if (!explore(board, 1)) { System.out.println("No solution found."); } else { System.out.println("One solution is as follows:"); System.out.println(board); } ...

Exercise solution, cont'd. // Recursively searches for a solution to 8 queens on this // board, starting with the given column, returning true if a // solution is found and storing that solution in the board. // PRE: queens have been safely placed in columns 1 to (col-1) public static boolean explore(Board board, int col) { if (col > board.size()) { return true; // base case: all columns are placed } else { // recursive case: place a queen in this column for (int row = 1; row <= board.size(); row++) { if (board.isSafe(row, col)) { board.place(row, col); // choose if (explore(board, col + 1)) { // explore return true; // solution found } b.remove(row, col); // un-choose return false; // no solution found