// Helene Martin, CSE 143 // Solves a maze using recursive backtracking. import java.io.*; import java.util.*; public class SolveMaze { public static void main(String[] args) throws FileNotFoundException { String fileText = ""; Scanner input = new Scanner(new File("maze1.txt")); while (input.hasNextLine()) { fileText += input.nextLine() + "\n"; } Maze maze = new Maze(fileText); maze.setAnimated(true); System.out.println(maze); System.out.println(); int startRow = 1; int startCol = 6; System.out.println("Start from (" + startRow + ", " + startCol + ")"); solve(maze, startRow, startCol); } // Finds a pathway out of the given maze from the given start location. // Pre: maze != null and startRow/Col are within the maze public static void solve(Maze maze, int startRow, int startCol) { explore(maze, startRow, startCol); } // choices: up, down, left, right // changing row/col // stop: // - a wall // - already explored // - I won! private static boolean explore(Maze maze, int row, int col) { System.out.println(maze); // for animation if (maze.isEscaped()) { return true; } else if (maze.isWall(row, col) || maze.isExplored(row, col)) { return false; } else { maze.setExplored(row, col); if (explore(maze, row - 1, col) || explore(maze, row + 1, col) || explore(maze, row, col - 1) || explore(maze, row, col + 1)) { maze.mark(row, col); System.out.println(maze); return true; } return false; } } }