//************************************************** solve using //recursion. Note: this solution unmarks the path upon reaching //dead ends, so in the end only the path is left marked. It is //possible to write a solution that does not un-mark its traces, //but instead it clones and restores the maze. public void solveRec() { 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. If a path is found, return true. Otherwise return false. public boolean solve(MazePos pos) { //base case if (!isInMaze(pos)) return false; if (isFinal(pos)) return true; if (!isClear(pos)) return false; //current position must be clear assert(isClear(pos)); //recurse //first mark this location mark(pos, V); //try to go south if (solve(pos.south())) { //we found a solution going south: if we want to leave the //maze clean, then unmark current cell and return; if we //want to mark the path in the maze, then don't unmark //mark(pos, C); return true; } //else west if (solve(pos.west())) { //we found a solution going west: if we want to leave the //maze clean, then unmark current cell and return; if we //want to mark the path in the maze, then don't unmark //return //mark(pos, C); return true; } //else north if (solve(pos.north())) { //we found a solution going north: if we want to leave the //maze clean, then unmark current cell and return; if we //want to mark the path in the maze, then don't unmark //return // mark(pos, C); return true; } //else east if (solve(pos.east())) { //we found a solution going east: if we want to leave the //maze clean, then unmark current cell and return; if we //want to mark the path in the maze, then don't unmark //return //mark(pos, C); return true; } //unmark all dead ends; since it was marked, the position must //have been clear mark(pos, C); //if none of the above returned, then there is no solution return false; } };