CSC 205 – Java Programming II

Slides:



Advertisements
Similar presentations
COSC2007 Data Structures II
Advertisements

Chapter 17 Recursion.
© 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.
Programming with Java. Problem Solving The purpose of writing a program is to solve a problem The general steps in problem solving are: –Understand the.
Announcements Assignment #4 is due tonight. Last lab program is going to be assigned this Wednesday. ◦ A backtracking problem.
Backtracking COP Backtracking  Backtracking is a technique used to solve problems with a large search space, by systematically trying and eliminating.
Swap I class Swap { public static void swap(int i, int j) {
Chapter 13 Linked Structures - Stacks. Chapter Scope Object references as links Linked vs. array-based structures Managing linked lists Linked implementation.
1 Applications of Recursion (Walls & Mirrors - 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.
Chapter 7 Arrays. © 2004 Pearson Addison-Wesley. All rights reserved11-2 Arrays Arrays are objects that help us organize large amounts of information.
Jan 12, 2012 Introduction to Collections. 2 Collections A collection is a structured group of objects Java 1.2 introduced the Collections Framework Collections.
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.
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 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.
1 Collection, Iterable, and Iterator Interfaces The Collection Interface and its Hierarchy The Iterable and Iterator Interfaces For-each Loops with Iterable.
Lab 1 Logbook ADT. OVERVIEW A monthly logbook consists of a set of entries, one for each day of the month.
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"?
1 Recursion Recursion is a powerful programming technique that provides elegant solutions to certain problems. Chapter 11 focuses on explaining the underlying.
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.
CSE 143 Lecture 18 More Recursive Backtracking slides created by Marty Stepp
CSE 143 Lecture 13 Recursive Backtracking slides created by Ethan Apter
Topic 13 Iterators. 9-2 Motivation We often want to access every item in a data structure or collection in turn We call this traversing or iterating over.
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.
Implementing an ADT Example: Sum-Constraint ADT Part II Ohad Barzilay May 2004.
CSE 143 read: 12.5 Lecture 18: recursive backtracking.
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.
1 Iterators & the Collection Classes. 2 » The Collection Framework classes provided in the JAVA API(Application Programmer Interface) contains many type.
CHAPTER 4: Linked Structures
Recursion -- Introduction
Recursive Exploration II
Recap: Solution of Last Lecture Activity
Data Structures and Algorithms
read: 12.5 Lecture 17: recursive backtracking
Fundamentals of Programming II Backtracking with Stacks
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.
CSC 113: Computer programming II
Analysis and design of algorithm
Introduction to Java Programming
Homework 8: Critters (cont.)
Jordi Cortadella Department of Computer Science
Exercise: Dice roll sum
Chapter 8 Recursion.
adapted from Recursive Backtracking by Mike Scott, UT Austin
CSE 143 Lecture 18 More Recursive Backtracking
CSE 143 Lecture 18 More Recursive Backtracking
Chap 2. Identifiers, Keywords, and Types
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"?
Loops CGS3416 Spring 2019 Lecture 7.
Announcements Assignment #4 is due tonight. Last lab program is going to be assigned this Wednesday. ◦ A backtracking problem.
Backtracking, Search, Heuristics
A type is a collection of values
Presentation transcript:

CSC 205 – Java Programming II Lecture 23 March 4, 2002

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. a sequence of chosen positions next positions in a predefined order retracing in reverse order

Illustration P13 P4 P12 P7 P3 P11 P6 P5 P2 Pi P10 P9 P8 P1 Position P0   P14 (GOAL)   P13 P4 P12 P7 P3 P11 P6 P5 P2 P10 P9 P8 P1 P0 1st Attempt 2nd Attempt     retracing Pi Position retracing (ORIG.)

Marking Visited Positions When a position is visited, it is marked as (potentially) being on a path to the goal code 9 If we discover otherwise, the marking must be undone, so that position will never again be visited. code 2

A Standard Solution A general-purpose BackTrack class is available User needs to supply An Application class A Position class to define an application-specific position An Iterator class to enumerate next position from the current position

The Application Interface 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);

The Application Interface // 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

The BackTrack Class import java.util.*; public class BackTrack {   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) { … … } // method tryToSolve } // class BackTrack

The tryToSolve Method 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;

Possible Moves 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, ...

An A-Maze-ing Application start 1 1 1 0 1 1 0 0 0 1 1 1 1 1 0 1 1 1 0 1 1 1 1 1 0 1 1 0 0 0 1 0 1 0 1 0 1 0 1 1 0 0 0 1 1 1 0 1 0 1 1 1 1 1 1 1 1 0 0 0 0 1 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 finish Maze notation 0: corridor 1: wall Iterator choices: north, east, south, west (in that order)

The Position Class public class Position { protected int row, column;   public Position () { row = 0; column = 0; } // constructor public Position (int row, int column) { this.row = row; this.column = 0; public int row () { return row; } public int column () { return column ; } }

The Maze Class 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

The Maze Class 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 { … … } // class MazeIterator } // class Maze

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

The MazeIterator Class // 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); break; // NORTH case 1: nextPosition = new Position (row, column+1); break; // EAST case 2: nextPosition = new Position (row+1, column); break; // SOUTH case 3: nextPosition = new Position (row, column-1); } // switch; return nextPosition; } // method next } // class MazeIterator

An Example 0-north X 3-west 1-east X X 2-south

Try Another Case start 1 1 1 0 1 1 0 0 0 1 1 1 1 1 0 1 1 1 0 1 1 1 1 1 0 1 1 0 0 0 1 0 1 0 1 0 1 0 1 1 0 0 0 1 1 1 0 1 0 1 1 1 1 1 1 1 1 0 0 0 0 1 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 finish Maze notation 0: corridor 1: wall Iterator choices: north, south, east, west (in that order)