/* This is the skeleton of a program that finds the path out of a maze in 3 possible ways: recursively, with a stack, and with a queue. This problem illustrates searching using stacks (depth-first search) and queues (breadth-first search), and recursively. Laura Toma csci 210 */ import java.util.Stack; import java.util.LinkedList; public class Maze { final static char C=' ', X='x', S='s', E='e', V='.'; //the maze private static char[][] maze = { {X, X, X, X, X, X, X, X, X, X}, {X, S, C, C, C, C, C, C, C, X}, {X, C, C, C, X, C, X, X, C, E}, {X, C, X, X, X, C, X, X, C, X}, {X, C, C, C, C, X, X, X, C, X}, {X, X, X, X, C, X, X, X, C, X}, {X, X, X, X, C, X, C, C, C, X}, {X, X, C, X, C, X, X, C, C, X}, {X, X, C, C, C, C, C, C, C, X}, {X, X, X, X, X, X, C, X, X, X} }; //the start position final static int START_I = 1, START_J = 1; //the end position final static int END_I = 2, END_J = 9; public static void main(String[] args) { Maze maze = new Maze(); maze.print(); System.out.println("\n\nFind a path using a stack: "); maze.solveStack(); System.out.println("\n\nFind a path using a queue: "); maze.solveQueue(); System.out.println("\n\nFind a path recursively: "); maze.solveRec(); } /* ****************************** */ //return the size of the maze (assume square) public int size() { return maze.length; } //print the maze public void print() { for (int i=0; i= 0 && i= 0 && j queue = new LinkedList(); //create the initial state and put it onto the queue MazePos ins = new MazePos(START_I, START_J); queue.add(ins); MazePos current; while (!queue.isEmpty()) { //take the first one in the queue current = queue.removeFirst(); if (isFinal(current)) break; //we found the solution //create all succesor of current and if valid add them to the queue MazePos next; next = current.north(); if (isInMaze(next) && isClear(next)) queue.addLast(next); } } //************************************************** //solve using recursion public void solveRec() { //call the recursive solver if (solve(new MazePos(START_I, START_J))) System.out.println("Got it: "); else System.out.println("You're stuck in the maze."); print(); } //find a path to exit the maze from this position. Works //recursively, by advancing to a neighbor and continuing from //there. Returns true if it finds a path, and false otherwise. public boolean solve(MazePos pos) { } }; class MazePos { int i, j; public MazePos(int i, int j) { this.i = i; this.j = j; }; public int i() { return i;} public int j() { return j;} public void print() { System.out.println("(" + i + "," + j + ")"); } public MazePos north() { return new MazePos(i-1, j); } public MazePos south() { return new MazePos(i+1, j); } public MazePos east() { return new MazePos(i, j+1); } public MazePos west() { return new MazePos(i, j-1); } };