TOWERS OF HANOI. : If n = 1, move disk 1 from pole 'A' to pole 'B'. else: 1.First, move n-1 disks from pole 'A' to pole 'C', using pole 'B' as.

Slides:



Advertisements
Similar presentations
COSC2007 Data Structures II
Advertisements

CSC 205 Programming II Lecture 10 Towers of Hanoi.
Chapter Objectives To learn about recursive data structures and recursive methods for a LinkedList class To understand how to use recursion to solve the.
Chapter 17 Recursion.
More Recursion: Permutations and Towers of Hanoi COP 3502.
© 2010 Pearson Addison-Wesley. All rights reserved. Addison Wesley is an imprint of CHAPTER 7: Recursion Java Software Structures: Designing and Using.
The Singleton Pattern II Recursive Linked Structures.
Recursion Ellen Walker CPSC 201 Data Structures Hiram College.
Backtracking COP Backtracking  Backtracking is a technique used to solve problems with a large search space, by systematically trying and eliminating.
Recursion Chapter 7. Spring 2010CS 2252 Chapter Objectives To understand how to think recursively To learn how to trace a recursive method To learn how.
Swap I class Swap { public static void swap(int i, int j) {
Chapter 2 Recursion: The Mirrors. © 2005 Pearson Addison-Wesley. All rights reserved2-2 Recursive Solutions Recursion is an extremely powerful problem-solving.
© 2006 Pearson Addison-Wesley. All rights reserved6-1 Chapter 6 Recursion as a Problem- Solving Technique.
Fall 2007CS 2251 Recursion Chapter 7. Fall 2007CS 2252 Chapter Objectives To understand how to think recursively To learn how to trace a recursive method.
Recursion Gordon College CPS212
Recursion. Recursive Solutions Recursion breaks a problem into smaller identical problems – mirror images so to speak. By continuing to do this, eventually.
Chapter 5 Recursion as a Problem-Solving Technique.
Chapter 13 Linked Structures - Stacks. Chapter Scope Object references as links Linked vs. array-based structures Managing linked lists Linked implementation.
Recursion Chapter 7. Chapter 7: Recursion2 Chapter Objectives To understand how to think recursively To learn how to trace a recursive method To learn.
Chapter 2 Recursion: The Mirrors. © 2005 Pearson Addison-Wesley. All rights reserved2-2 Recursive Solutions Recursion is an extremely powerful problem-
Recursion Chapter 5.
1 Identifiers  Identifiers are the words a programmer uses in a program  An identifier can be made up of letters, digits, the underscore character (
1 CMPSCI 187 Computer Science 187 Introduction to Introduction to Programming with Data Structures Lecture 11: Stacks and Mazes Announcements 1.Midterm.
Recursion Chapter Nature of Recursion t Problems that lend themselves to a recursive solution have the following characteristics: –One or more.
Chapter 2 Recursion: The Mirrors. © 2005 Pearson Addison-Wesley. All rights reserved2-2 Recursive Solutions Recursion is an extremely powerful problem-
Chapter 7 Arrays. © 2004 Pearson Addison-Wesley. All rights reserved11-2 Arrays Arrays are objects that help us organize large amounts of information.
Recursion Chapter 7. Chapter Objectives  To understand how to think recursively  To learn how to trace a recursive method  To learn how to write recursive.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley. Ver Chapter 2: Recursion: The Mirrors.
CSE 143 Lecture 17 More Recursive Backtracking reading: "Appendix R" on course web site slides created by Marty Stepp and Hélène Martin
MT311 Java Application Development and Programming Languages Li Tak Sing ( 李德成 )
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.
Announcements This Wednesday, Class and Labs are cancelled! The last lab is due this Wednesday … how many people are planning on doing it? Finally posted.
Sudoku Jordi Cortadella Department of Computer Science.
CHAPTER 5 ArrayLists.
CHAPTER 4 RECURSION. BASICALLY, A FUNCTION IS RECURSIVE IF IT INCLUDES A CALL TO ITSELF.
CHAPTER 4 RECURSION. BASICALLY, A METHOD IS RECURSIVE IF IT INCLUDES A CALL TO ITSELF.
Chapter 5 Recursion. Basically, a method is recursive if it includes a call to itself.
Introduction to Java Lecture Notes 3. Variables l A variable is a name for a location in memory used to hold a value. In Java data declaration is identical.
(c) University of Washington15-1 CSC 143 Java List Implementation via Arrays Reading: 13.
Building Java Programs Appendix R Recursive backtracking.
1 Recursion Recursion is a powerful programming technique that provides elegant solutions to certain problems. Chapter 11 focuses on explaining the underlying.
Recursion as a Problem- Solving Technique Chapter 5 Data Structures and Problem Solving with C++: Walls and Mirrors, Carrano and Henry, © 2013.
COS 312 DAY 19 Tony Gauvin. Ch 1 -2 Agenda Questions? Capstone Progress reports over due Assignment 6 Posted – Due April 16 Layers using non-opaque panels.
Iteration Abstraction SWE Software Construction Fall 2009.
Recursion Chapter 17 Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013.
Linked Structures Chapter 13 Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013.
CSE 143 read: 12.5 Lecture 18: recursive backtracking.
Chapter 2 Recursion: The Mirrors. © 2005 Pearson Addison-Wesley. All rights reserved2-2 Recursive Solutions Recursion is an extremely powerful problem-solving.
Data Abstraction and Problem Solving with JAVA Walls and Mirrors Frank M. Carrano and Janet J. Prichard © 2001 Addison Wesley Data Abstraction and Problem.
COS 312 DAY 24 Tony Gauvin. Ch 1 -2 Agenda Questions? Assignment 6 Corrected Assignment 7 (bonus) – Due May 11 – Will be scored on 15 point scale, points.
CHAPTER 4: Linked Structures
Recursion -- Introduction
Recursive Exploration II
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
Java Software Structures: John Lewis & Joseph Chase
Chapter 4 Linked Structures - Stacks
7.4 Problem Solving with Recursion
Building Java Programs
Chapter 12 Recursion (methods calling themselves)
Chapter 4 Linked Structures - Stacks
null, true, and false are also reserved.
Chapter 8 Recursion.
adapted from Recursive Backtracking by Mike Scott, UT Austin
ITI Introduction to Computing II Lab-12
Recursive Thinking.
CSC 205 – Java Programming II
Recursion: The Mirrors
Presentation transcript:

TOWERS OF HANOI

: If n = 1, move disk 1 from pole 'A' to pole 'B'. else: 1.First, move n-1 disks from pole 'A' to pole 'C', using pole 'B' as a temporary. 2.Then move disk n from pole 'A' to pole 'B'. 3.Finally, move n-1 disks from pole 'C' to pole 'B', using pole 'A' as a temporary.

origin = 'A' origin = 'A' destination = 'B' temporary = 'C' Then the general strategy for moving n disks from origin to destination is as follows:

If n is 1, move disk 1 from origin to destination. Otherwise, 1.Move n - 1 disks (one at a time) from origin to temporary; 2. Move disk n from origin to destination; 3. Move n-1 disks (one at a time) from temporary to destination.

// Precondition: n > 0. Otherwise, IllegalArgumentException has // been thrown. // Postcondition: the steps needed to move n disks from pole orig // to pole dest have been written out. Pole temp is // used for temporary storage. The worstTime (n) is // O (2 n ). public void move (int n, char orig, char dest, char temp) { if (n <= 0) throw new IllegalArgumentException( ); if (n == 1) gui.println ("Move disk 1 from " + orig + " to " + dest); else { move (n ‑ 1, orig, temp, dest); gui.println ("Move disk " + n + " from " + orig + " to " + dest); move (n ‑ 1, temp, dest, orig) ; } // else } // method move

THE TOTAL NUMBER OF CALLS TO move IS: n … + 2 n-1 =  2 i i=0

n-1  2 i = 2 n - 1 i=0 SEE EXAMPLE 6 OF APPENDIX 1 FOR A PROOF BY MATHEMATICAL INDUCTION.

WE CONCLUDE THAT worstTime (n) is O (2 n ), AND 2 n IS THE SMALLEST UPPER BOUND OF worstTime (n).

BACKTRACKING

Backtracking Backtracking is the strategy of trying to reach a goal by a sequence of chosen positions, with re-tracing in reverse order of position that cannot lead to the goal.

P14 (GOAL) P13 P4 P12 P7 P3 P11 P6 P5 P2 P10 P9 P8 P1 P0

WHEN A POSITION IS VISITED, IT IS MARKED AS (POTENTIALLY) BEING ON A PATH TO THE GOAL. IF WE DISCOVER OTHERWISE, THE MARKING MUST BE UNDONE, SO THAT POSITION WILL NEVER AGAIN BE VISITED.

GENERAL-PURPOSE Backtrack CLASS USER SUPPLIES: AN Application OBJECT A Position OBJECT AN Iterator OBJECT

import java.util.*; public class BackTrack { Application app; // Postcondition: this BackTrack has been initialized from app. public BackTrack (Application app) { this.app = app; } // constructor

// Postcondition: a solution going through pos has been attempted. public boolean tryToSolve (Position pos) { boolean success = false; Iterator itr = app.iterator (pos); while (!success && itr.hasNext()) { pos = (Position)itr.next(); if (app.valid (pos)) { app.record (pos); if (app.done (pos)) success = true; else { success = tryToSolve (pos); if (!success) app.undo (pos); } // not done } // a valid position } // while return success; } // method tryToSolve } // class BackTrack

POSSIBLE MOVES FROM pos IN tryToSolve: SUCCESS, IF ONE OF THOSE MOVES IS A GOAL POSITION; HOPEFUL, IF ONE OF THOSE MOVES IS VALID BUT NOT A GOAL POSITION. RECURSIVE CALL! FAILURE, IF NONE OF THOSE MOVES IS ON A PATH TO GOAL;

IMPORTANT: WHEN A RETURN IS MADE, THE PRE-CALL VALUE OF pos IS RESTORED. SO THE PREVIOUSLY VISITED POSITIONS ARE AVAILABLE, TO BE PRINTED AS PART OF THE PATH TO THE GOAL, TO BE UNDONE,...

import java.util.*; public interface Application { // Postcondition: true has been returned if pos could be on a path to a // goal position. // Otherwise, false has been returned. public boolean valid (Position pos); // Postcondition: the position specified by pos has been marked as //being on a path to a goal position. public void record (Position pos); // Postcondition: true has been returned if pos is a goal position. //Otherwise, false has been returned. public boolean done (Position pos);

// Postcondition: the position specified by pos has been marked //as not being on a path to a goal position. public void undo (Position pos); // Postcondition: a string representation of this Application has //been returned. public String toString(); // Postcondition: an iterator over the positions directly accessible //from pos has been returned. public Iterator iterator (Position pos); } // interface Application

MAZE SEARCHING: 1 = CORRIDOR; 0 = WALL start finish ITERATOR CHOICES: NORTH, EAST, SOUTH, WEST

SOLUTION: 9 = PATH; 2 = DEAD END

public class Maze implements Application { protected final byte WALL = 0; protected final byte CORRIDOR = 1; protected final byte PATH = 9; protected final byte TRIED = 2; protected Position finish; protected byte[ ][ ] grid;

public boolean valid (Position pos) { if (pos.row() >= 0 && pos.row() < grid.length && pos.column() >= 0 && pos.column() < grid [0].length && grid [pos.row()][pos.column()] == CORRIDOR) return true; return false; } // method valid public void record (Position pos) { grid [pos.row()][pos.column()] = PATH; } // method record public boolean done (Position pos) { return pos.row() == finish.row() && pos.column() == finish.column(); } // method done

private class MazeIterator implements Iterator { int row, column, count = 0; public MazeIterator (Position pos) { row = pos.row(); column = pos.column(); } // constructor public boolean hasNext() { return count < 4; } // method hasNext

// Precondition: 0 <= count <= 3. // Postcondition: the choice for the next Position has // been returned. public Object next() { Position nextPosition = new Position(); switch (count++) { case 0: nextPosition = new Position (row-1, column); // NORTH break; case 1: nextPosition = new Position (row, column+1); // EAST break; case 2: nextPosition = new Position (row+1, column); // SOUTH break; case 3: nextPosition = new Position (row, column-1); // WEST } // switch; return nextPosition; } // method next

GROUP EXERCISE: SHOW FINAL GRID start finish ITERATOR CHOICES: NORTH, SOUTH, EAST, WEST