1 CMPSCI 187 Computer Science 187 Introduction to Introduction to Programming with Data Structures Lecture 11: Stacks and Mazes Announcements 1.Midterm.

Slides:



Advertisements
Similar presentations
CS Data Structures I Chapter 6 Stacks I 2 Topics ADT Stack Stack Operations Using ADT Stack Line editor Bracket checking Special-Palindromes Implementation.
Advertisements

Senem Kumova Metin Spring2009 STACKS AND QUEUES Chapter 10 in A Book on C.
Formal Language, chapter 4, slide 1Copyright © 2007 by Adam Webber Chapter Four: DFA Applications.
Stacks Based on Koffmann and Wolfgang Chapter 5. Chapter 5: Stacks2 Chapter Outline The Stack data type and its four methods: push(E), pop(), peek(),
Written by: Dr. JJ Shepherd
Elementary Data Structures CS 110: Data Structures and Algorithms First Semester,
Stacks Chapter 5. Chapter Objectives  To learn about the stack data type and how to use its four methods: push, pop, peek, and empty  To understand.
CHAPTER 3 Stacks. Chapter Objectives  To learn about the stack data type and how to use its four methods:  push  pop  peek  empty  To understand.
Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Eighth Edition by Tony Gaddis,
Stacks Chapter 5. Chapter 5: Stacks2 Chapter Objectives To learn about the stack data type and how to use its four methods: push, pop, peek, and empty.
Stacks Chapter 5. Chapter 5: Stacks2 Chapter Objectives To learn about the stack data type and how to use its four methods: push, pop, peek, and empty.
Unit 11 1 Unit 11: Data Structures H We explore some simple techniques for organizing and managing information H This unit focuses on: Abstract Data Types.
Stacks Cmput Lecture 18 Department of Computing Science University of Alberta ©Duane Szafron 2000 Some code in this lecture is based on code from.
Fall 2007CS 2251 Stacks Chapter 5. Fall 2007CS 2252 Chapter Objectives To learn about the stack data type and how to use its four methods: push, pop,
Fall 2007CS 2251 Stacks Chapter 5. Fall 2007CS 2252 Chapter Objectives To learn about the stack data type and how to use its four methods: push, pop,
CHAPTER 6 Stacks Array Implementation. 2 Stacks A stack is a linear collection whose elements are added and removed from one end The last element to be.
Chapter 13 Linked Structures - Stacks. Chapter Scope Object references as links Linked vs. array-based structures Managing linked lists Linked implementation.
Building Java Programs
Chapter 3 Stacks.
CHAPTER 3 Stacks MIDTERM OCTOBER 17 IN LAB. Chapter Objectives  To learn about the stack data type and how to use its four methods:  push  pop  peek.
Abstract Data Types (ADTs) and data structures: terminology and definitions A type is a collection of values. For example, the boolean type consists of.
Topic 3 The Stack ADT.
Implementing Stacks Ellen Walker CPSC 201 Data Structures Hiram College.
Lecture Objectives To understand how Java implements a stack To learn how to implement a stack using an underlying array or linked list Implement a simple.
Chapter 7 Stacks I CS Data Structures I COSC 2006 April 22, 2017
Java: Chapter 1 Computer Systems Computer Programming II.
Problem of the Day  What do you get when you cross a mountain climber and a grape?
COMP 121 Week 13: Stacks. Objectives Learn about the stack data type and how to use its four methods: push, pop, peek, and empty Understand how Java implements.
6 Stack ADTs  Stack concepts  Stack applications  Stack ADTs: requirements, contracts  Implementations of stacks: using arrays and linked-lists  Stacks.
Chapter 7 Stacks. © 2004 Pearson Addison-Wesley. All rights reserved 7-2 The Abstract Data Type: Developing an ADT During the Design of a Solution Specifications.
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
© 2004 Goodrich, Tamassia Stacks. © 2004 Goodrich, Tamassia Stacks2 Abstract Data Types (ADTs) An abstract data type (ADT) is an abstraction of a data.
CSE 12 – Basic Data Structures Cynthia Bailey Lee Some slides and figures adapted from Paul Kube’s CSE 12 CS2 in Java Peer Instruction Materials by Cynthia.
Stacks. A stack is a data structure that holds a sequence of elements and stores and retrieves items in a last-in first- out manner (LIFO). This means.
Lecture objectives  Collections interface  Learn about stacks and their methods:  push  pop  peek  Empty  Analyze stack applications and why stacks.
30 May Stacks (5.1) CSE 2011 Winter Stacks2 Abstract Data Types (ADTs) An abstract data type (ADT) is an abstraction of a data structure An.
1 Chapter 20 Lists, Stacks, Queues Lecture 7 Dr. Musab Zghoul برمجة هيكلية.
“Planning is bringing the future into the present so that you can do something about it now.” – Alan Lakein Thought for the Day.
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.
CS 367 Introduction to Data Structures Lecture 5.
Computer Science 209 Software Development Inheritance and Composition.
Lecture Objectives  To understand how Java implements a stack  To learn how to implement a stack using an underlying array or linked list  Implement.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington Summary and Exam COMP 102.
Written by: Dr. JJ Shepherd
ITI Introduction to Computing II Lab-5 Dewan Tanvir Ahmed University of Ottawa.
Copyright © Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Java From Control Structures through Data Structures by Tony.
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.
“The desire for safety stands against every great and noble enterprise.” – Tacitus Thought for the Day.
Click to edit Master text styles Stacks Data Structure.
Linked Structures Chapter 13 Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013.
1 Data Structures and Algorithms Stack. 2 The Stack ADT Introduction to the Stack data structure Designing a Stack class using dynamic arrays Linked Stacks.
CHAPTER 4: Linked Structures
Stacks Chapter 5.
MIDTERM OCTOBER 17 IN LAB Chapter 3 Stacks.
Recursive Exploration II
Chapter 6: The Stack Abstract Data Type
Exceptions, Interfaces & Generics
Stacks.
Chapter 6: The Stack Abstract Data Type
The Stack ADT. 3-2 Objectives Define a stack collection Use a stack to solve a problem Examine an array implementation of a stack.
Fundamentals of Programming II Backtracking with Stacks
CSE 143 Lecture 19 More Recursive Backtracking
Chapter 4 Linked Structures - Stacks
Java Methods Stacks and Queues A & AB Object-Oriented Programming
Chapter 4 Linked Structures - Stacks
null, true, and false are also reserved.
MIDTERM OCTOBER 11 IN LAB Chapter 3 Stacks.
Stacks public interface Stack { public boolean empty();
CHAPTER 3: Collections—Stacks
Presentation transcript:

1 CMPSCI 187 Computer Science 187 Introduction to Introduction to Programming with Data Structures Lecture 11: Stacks and Mazes Announcements 1.Midterm exam: October 29 in class 2.A new OWL assignment is up, due 10/20. 3.Help for studying for the midterm is available on the WIKI.

2 CMPSCI 187 Implementing Stacks l Book shows four possibilities: F As an extension to Vector F With a list component F Using an array F As a linked structure l Included in these notes but not covered in class l Book defines a stack interface on page 259; Java has no stack interface

3 CMPSCI 187 Implementing Stack as Extension of Vector Collection hierarchy includes java.util.Stack The Vector class offers a growable array of objects Elements of a Vector accessed by index l Size can grow or shrink as needed That is: Vector is just like ArrayList

4 CMPSCI 187 Implementing Stack as Extension of Vector (2) Top element of the Stack is at the highest index

5 CMPSCI 187 Stack Code public class Stack extends Vector { public E push (E e) { add(e); return e; } public E pop () throws EmptyStackException { try { return remove(size()-1); } catch (ArrayIndexOutOfBoundsException ex) { throw new EmptyStackException(); }...

6 CMPSCI 187 Stack Code (2) public class Stack extends Vector {... public E peek () throws EmptyStackException { try { return get(size()-1); } catch (ArrayIndexOutOfBoundsException ex) { throw new EmptyStackException(); } public boolean empty () { return size() == 0; }

7 CMPSCI 187 Implementing Stack with a List Can use ArrayList, Vector, or LinkedList :  All implement the List interface Name of class illustrated in text is ListStack ListStack is an adapter class F Adapts methods of another class to... F Gives different names to essentially the same operations

8 CMPSCI 187 ListStack Code public class ListStack implements StackInt { private List list; public ListStack () { list = new ArrayList (); // or new Vector or new LinkedList } public E push (E e) { list.add(e); return e; }...

9 CMPSCI 187 ListStack Code (2) public E peek () { if (empty()) throw new EmptyStackException(); return list.get(list.size()-1); } public E pop () { if (empty()) throw new EmptyStackException(); return list.remove(list.size()-1); } public boolean empty () { return list.size() == 0; }

10 CMPSCI 187 Implementing Stack Using an Array l Must allocate array with some default capacity l Need to keep track of the top of the stack l Have no size method, so must track size Similar to growable PhoneDirectory Why not just use vector?

11 CMPSCI 187 Implementing Stack Using an Array (2)

12 CMPSCI 187 ArrayStack Code public class ArrayStack implements StackInt { private static final int INITIAL_CAPACITY = 10; private E[] data = (E[]) new Object[INITIAL_CAPACITY]; private int top = -1; public ArrayStack () { } public boolean empty () { return top < 0; }... }

13 CMPSCI 187 ArrayStack Code (2) public E push (E e) { if (++top == data.length) reallocate(); return data[top] = e; } public E pop () { if (empty()) throw new EmptyStackException(); return data[top--]; } public E peek () { if (empty()) throw new EmptyStackException(); return data[top]; }

14 CMPSCI 187 ArrayStack Code (3) private void reallocate () { E[] newData = (E[]) new Object[data.length*2]; System.arraycopy(data, 0, newData, 0, data.length); data = newData; }

15 CMPSCI 187 Implementing Stack as a Linked Structure We can implement Stack using a linked list:

16 CMPSCI 187 LinkedStack Code public class LinkedStack implements StackInt { private Node top = null; public LinkedStack () { } public boolean empty () { return top == null; } public E push (E e) { top = new Node (e, top); return e; }... }

17 CMPSCI 187 LinkedStack Code (2) public E pop () { if (empty()) throw new EmptyStackException(); E result = top.data; top = top.next; return result; } public E peek () { if (empty()) throw new EmptyStackException(); return top.data; }

18 CMPSCI 187 LinkedStack Code (3) private static class Node { private E data; private Node next; Node (E data, Node next) { this.data = data; this.next = next; }

19 CMPSCI 187 Comparison of Stack Implementations Vector is a poor choice: exposes Vector methods Likewise, extending other List classes exposes their methods Using a List as a component avoids exposing  LinkedStack operations are O(1) H But Node objects add space overhead  ArrayList component is perhaps easiest  Still some space overhead ( Stack + ArrayList ) F Array as a component best in space and time H But somewhat harder to implement

20 CMPSCI 187

21 CMPSCI 187 M. C. Escher: Relativity

22 CMPSCI 187 Isabelle de Beaufort's environmental maze in the village of reignac sur Indre in France.

23 CMPSCI 187 An Application of Stacks: Solving a Maze Mazes and Labyrinths: what’s the difference? Enter Exit

24 CMPSCI 187 The Palace at Knossos Greek myth of Thesesus and the Minotaur.

25 CMPSCI 187 What’s a Plausible Approach to Solving a Maze? Enter Exit

26 CMPSCI 187 Solving a Maze Represent as an array with black and white spaces Important decision / choice points: which path to follow? North South East West Dead-ends No-brainers Special Path Wall

27 CMPSCI 187 U N E S W 0 1 U N E S W U N E S W The General Cases What direction can we move in?  not walls  not back where we came from (=deadend) (=no choice) (=choice) ‘allowed’ directions North South East West

28 CMPSCI 187 What to do in each of the cases? No-Brainer Case:  only one direction that we can move in.  suppose I know my current location and the direction to move?  I want to ‘take a step’ ….what’s my next coordinates? U U columns rows row col row-1 col row+1 col-1 row col+1 ‘next’ position Helper Method N E S W North Helper Method

29 CMPSCI 187 What to do in each of the cases? The ‘choice’ or ‘decision’ case  need to remember all possibilities[push each onto a stack]  need to choose one [pop top one off the stack]  need to take a step in that direction U N E S W 1 0 possible next steps location direction location direction ‘choice’ stack location direction location direction ‘choice’ stack location direction location direction Helper Method POP

30 CMPSCI 187 What to do in each of the cases? Dead-end case  need to go back to previous choice point and explore an alternative path [BACKTRACKING]  if there are NO previous choice points, then there is no path through the maze! U N E S W 0 0 U Where’s the next alternative(s) from the previous choice point?? ON THE TOP OF THE STACK. ‘choice’ stack location direction ‘choice’ stack location direction POP Becomes new location and direction

31 CMPSCI 187 Putting it all together Given current location (=start) and goal location Move one step into maze  get current direction given starting location  step in that direction Repeat forever v Is current location the goal? if yes, report it found and stop. v Get the allowed directions from here. v Handle the cases  Only one choice.  get direction to go in  step in that direction  More than one choice  push a decision point onto the stack for EACH possible direction  pop the top location and set current location and direction accordingly  take a step in that direction  No choices (dead-end)  If the stack is not empty, get top element (pop), set current location and direction, and step in that direction  If the stack IS empty, report failure and stop. Helper Methods

32 CMPSCI 187 The Maze Program: Classes Used All the stack classes: LinkedStack.java, StackfullException.java, StackEmptyException.java, Node.java, Stack.java The interface defining compass directions CardinalDirections.java: int NORTH = 0; int EAST = 1; int SOUTH = 2; int WEST = 3; The class defining a location:  Location.java: protected int row; protected int col; The class defining the structure of the information pushed onto the stack  decBlock.java: myLocation = currPos; myDir=myDirection; The class defining the maze itself:  Maze.java A test program  TestMaze.java: reads in maze, prints it, and solves it,

33 CMPSCI 187 A Maze in a File #. ##### #.#.#..#.# #.... ##### The size of the maze (rows, columns) The starting square (row, col) The goal square The symbol used for wall and path The maze itself

34 CMPSCI 187 Maze.java public class Maze implements CardinalDirections {protected char [ ][ ] maze; //the maze; upper left corner of maze is (0,0) protected int nrows, ncols; //size of maze protected location start; //(row,col) coordinates of starting point protected location goal; //(row,col) coordinates of goal (i.e. the exit from the maze) protected char wallSym; //symbol used in file to designate a wall; protected char pathSym; //symbol used in file to designate a path; protected boolean debug; //debug flag...if true, debugging statements are on; private int currDir; //my current direction : North=0, East=1, etc. private location currLoc; //my current location in the maze (location is a row and column) private int[] allowed; //array of four possible directions I can move in from my //current location with 0 indicating I can't go that way, and 1 indicating //I can in order NESW private LinkedStack choices; //the stack to be used in the method mazeSolve() private BufferedReader B; //reader for maze file private String fname; //file that the maze is on

35 CMPSCI 187 The public methods of Java.maze public Maze(String fileName, boolean IsDebugOn) throws IOException  sets up a buffered reader for the maze file  reads the array size, start location, goal location, and symbols from file  creates the maze array  creates the ‘choices’ stack public char[ ][ ] getMaze()  ‘get’ method which returns the two dimensional maze array public void readMaze() throws IOException  reads the maze array itself from the file and fills maze array public void writeMaze ()  prints the maze public boolean mazeSolve()  returns true if the maze has a path from start to goal and false otherwise public void closeFile() throws IOException  closes the maze file and frees I/O resources

36 CMPSCI 187 The private methods of Maze.Java private char toChar(String s)  returns the character equivalent of the first element of s private int getDirection()  returns the direction corresponding to location of first allowed direction in the allowed direction vector private void step ()  given a direction, moves us to the next maze square in that direction by modifying the current location private int getStartDir()  given the starting location, determine the direction to step into the maze private boolean isGoal()  compares current location and goal location; returns true if they match private void getAllowed()  returns the four element vector indicating whether or not (1 or 0) we can move in the corresponding direction from the current location private void updateStack()  for every allowed direction from the current location, pushes a location block onto the stack. Each block contains the current location and a direction to move in.

37 CMPSCI 187 The mazeSolve method public boolean mazeSolve() { currDir = getStartDir(); //get direction to go in to step into the maze step(); //step into it while (true) { if(isGoal()) return true; //we’ve found a solution, so we’re done. getAllowed(); //where can I go from here? int sum=sumAllowed(); //add up the elements of the ‘allowed’ vector switch(sum) { case 0: //We have nowhere to go from this square (deadend) { if( !choices.isEmpty()) //Go back to previous decision point- search from there. { decBlock old = (decBlock) choices.pop(); currLoc = old.decLocation; //update our location and direction currDir = old.myDir; step(); } else return false; //if stack is empty, nowhere to go back to, and no solution break; }

38 CMPSCI 187 Maze.java, continued case 1: //We have only one direction I can go in, so do it. { currDir=getDirection(); step(); break; } default: //We have more than one direction to go in. { updateStack(); //push a block for each alternative (save them) decBlock old = (decBlock) choices.pop(); //get one of the ones just pushed //and start exploring. currLoc = old.decLocation; currDir = old.myDir; step(); break; } }//end switch }// end while }//end mazeSolve

39 CMPSCI 187 A Test Program import java.io.*; public class test_Maze { public static void main(String args[]) throws IOException { boolean debug; String str=null; String fileName = args[0]; try {str = args[1];} catch (ArrayIndexOutOfBoundsException e) {str="false";} if (str.equalsIgnoreCase("true")) debug=true; else debug=false;

40 CMPSCI 187 Test Program: The Important Part Maze mazer = new Maze(fileName, debug); mazer.readMaze(); // read the Maze mazer.closeFile(); //close out the input file mazer.writeMaze(); //write the maze to the console if (mazer.mazeSolve()) //solve the maze System.out.println("This maze HAS a solution"); else System.out.println("This maze DOES NOT HAVE a solution"); }

41 CMPSCI 187 Results Reading Maze from file:maze12x12.txt Size: 12 rows by 12 columns. Start location for maze: [2, 0] Goal location for maze: [10, 11] # is used to designate a wall. is used to designate a path Finished Reading Printing maze of size 12 rows by 12 columns ############ # #..########## #.#.#......# #.#.######## # # ######.##### #......#...# ######.#.#.# # #.# ##########.. ############ Done This maze HAS a solution

42 CMPSCI 187 No Results Reading Maze from file:maze12x12_noexit.txt Size: 12 rows by 12 columns. Start location for maze: [2, 0] Goal location for maze: [10, 11] # is used to designate a wall. is used to designate a path Finished Reading Printing maze of size 12 rows by 12 columns ############ # #..########## #.#.#......# #.#.######## # # ######.##### #......#...# ######.#.#.# # ### ##########.. ############ Done This maze DOES NOT HAVE a solution Change from previous example.