The shortest way to solve the maze
This class uses graphics to print a maze. The program will run 3 times. After the first save, I save an array of steps that counts the number of times the character moves to a point. Then I write this array to a file. Before the next run, I open the file. I need to use the contents of the file to "find out" where to go to the next test (ie Avoid dead ends, find a fast path to the end).
I have a hasBadBranch () method that I want to return true for all intersections that have branches (north, south, east and west from the intersection) with "steps"> 1. I get the array index from and the character no longer traverses the maze correctly when I add the hasBadBranch condition to my solve () method. If anyone sees any flaws in my logic, I would be very grateful for your feedback. Thank.
public class Maze extends JFrame {
private static final int MAX_WIDTH = 255;
private static final int MAX_HEIGHT = 255;
private char[][] maze = new char[MAX_HEIGHT][MAX_WIDTH];
private int[][] steps = new int[MAX_HEIGHT][MAX_WIDTH];
private Random random = new Random();
private JPanel mazePanel = new JPanel();
private int width = 0;
private int height = 0;
private boolean step = false;
private boolean timerFired = false;
private Timer timer;
private final int TIMER_DELAY = 20;
private final int SPRITE_WIDTH = 25;
private final int SPRITE_HEIGHT = 25;
private BufferedImage mazeImage;
private ImageIcon ground = new ImageIcon("sprites/ground.png");
private ImageIcon wall1 = new ImageIcon("sprites/cactus.png");
private ImageIcon wall2 = new ImageIcon("sprites/rock.png");
private ImageIcon finish = new ImageIcon("sprites/well.png");
private ImageIcon south1 = new ImageIcon("sprites/cowboy-forward-1.png");
private ImageIcon south2 = new ImageIcon("sprites/cowboy-forward-2.png");
private ImageIcon north1 = new ImageIcon("sprites/cowboy-back-1.png");
private ImageIcon north2 = new ImageIcon("sprites/cowboy-back-2.png");
private ImageIcon west1 = new ImageIcon("sprites/cowboy-left-1.png");
private ImageIcon west2 = new ImageIcon("sprites/cowboy-left-2.png");
private ImageIcon east1 = new ImageIcon("sprites/cowboy-right-1.png");
private ImageIcon east2 = new ImageIcon("sprites/cowboy-right-2.png");
private long startTime;
private long currentTime;
private static final int MAX_TIME = 500000;
/**
* Constructor for class Maze. Opens a text file containing the maze, then
* attempts to solve it.
*
* @param fname String value containing the filename of the maze to open.
*/
//Notes to user:
//delete steps.txt BEFORE testing begins and AFTER third run of program
//use appropriate file paths
public Maze(String fname) throws FileNotFoundException, IOException {
openMaze(fname);
mazeImage = printMaze();
readInFile();
timer = new Timer(TIMER_DELAY, new TimerHandler()); // setup a Timer to slow the animation down.
timer.start();
addWindowListener(new WindowHandler()); // listen for window event windowClosing
setTitle("Cowboy Maze");
setSize(width * SPRITE_WIDTH + 10, height * SPRITE_HEIGHT + 30);
setVisible(true);
add(mazePanel);
setContentPane(mazePanel);
solveMaze();
}
public void readInFile() throws FileNotFoundException, IOException {
//Note to user: adjust file path accordingly
File stepsFile = new File("C:\\Users\\Ashley Bertrand\\Desktop\\Data Structures\\Lab6\\mazeStartSourceMazesGraphics\\steps.txt");
if (stepsFile.isFile()) {
Scanner scanner = new Scanner(stepsFile);
int lineCount = 0;
while (scanner.hasNextLine()) {
String[] currentLine = scanner.nextLine().trim().split("\\s+");
for (int i = 0; i < currentLine.length; i++) {
steps[lineCount][i] = Integer.parseInt(currentLine[i]);
}
lineCount++;
}
System.out.println("Contents of steps.txt:");
for (int m = 0; m < width; m++) {
for (int n = 0; n < height; n++) {
System.out.print(steps[m][n]);
}
System.out.println();
}
System.out.println();
} else {
System.out.println("Running first trial so steps.txt does not exist");
}
}
/**
* Called from the operating system. If no command line arguments are
* supplied, the method displays an error message and exits. Otherwise, a
* new instance of Maze() is created with the supplied filename from the
* command line.
*
* @param args[] Command line arguments, the first of which should be the
* filename to open.
*/
public static void main(String[] args) throws FileNotFoundException, IOException {
int runny = 1;
if (args.length > 0) {
new Maze(args[0]);
} else {
System.out.println();
System.out.println("Usage: java Maze <filename>.");
System.out.println("Maximum Maze size:" + MAX_WIDTH + " x " + MAX_HEIGHT + ".");
System.out.println();
System.exit(1);
}
}
/**
* Finds the starting location and passes it to the recursive algorithm
* solve(x, y, facing). The starting location should be the only '.' on the
* outer wall of the maze.
*/
public void solveMaze() throws FileNotFoundException {
boolean startFound = false;
if (!startFound) {
for (int i = 0; i < width; i++) { // look for the starting location on the top and bottom walls of the Maze.
if (maze[0][i] == '.') {
maze[0][i] = 'S';
steps[0][i]++;
preSolve(i, 0, "south");
startFound = true;
} else if (maze[height - 1][i] == '.') {
maze[height - 1][i] = 'S';
steps[height - 1][i]++;
preSolve(i, height - 1, "north");
startFound = true;
}
}
}
if (!startFound) {
for (int i = 0; i < height; i++) { // look for the starting location on the left and right walls of the Maze.
if (maze[i][0] == '.') {
maze[i][0] = 'S';
steps[i][0]++;
preSolve(0, i, "east");
startFound = true;
} else if (maze[i][width - 1] == '.') {
maze[i][width - 1] = 'S';
steps[i][width - 1]++;
preSolve(width - 1, i, "west");
startFound = true;
}
}
}
if (!startFound) {
System.out.println("Start not found!");
}
}
public void preSolve(int x, int y, String facing) throws FileNotFoundException {
Scanner input = new Scanner(System.in);
System.out.println("Press 1 to start");
input.nextLine();
startTime = System.currentTimeMillis();
solve(x, y, facing);
}
/**
* Recursive algorithm to solve a Maze. Places an X at locations already
* visited. This algorithm is very inefficient, it follows the right hand
* wall and will never find the end if the path leads it in a circle.
*
* @param x int value of the current X location in the Maze.
* @param y int value of the current Y location in the Maze.
* @param facing String value holding one of four cardinal directions
* determined by the current direction facing.
*/
private void solve(int x, int y, String facing) throws FileNotFoundException {
Graphics2D g2 = (Graphics2D) mazePanel.getGraphics(); //don't mess with the next
while (!timerFired) { // wait for the timer.
try {
Thread.sleep(10);
} catch (Exception e) {
}
}
timerFired = false;
currentTime = System.currentTimeMillis();
if ((currentTime - startTime) > MAX_TIME) {
closingMethod();
}
if (maze[y][x] != 'F') { //this is if it doesn't find the finish on a turn.........
g2.drawImage(mazeImage, null, 0, 0);
g2.drawImage(printGuy(facing), x * SPRITE_WIDTH, y * SPRITE_HEIGHT, null, null);
mazePanel.setSize(width * SPRITE_WIDTH + 10, height * SPRITE_HEIGHT + 30);
maze[y][x] = 'X'; // mark this spot as visited. This is how you can keep track of where you've been.
if (facing.equals("east")) {
if (maze[y + 1][x] != '#' && maze[y + 1][x] != '%' && maze[y + 1][x] != 'S' && !hasBadBranch(y+1, x)) {
steps[y + 1][x]++;
solve(x, y + 1, "south");
} else if (maze[y][x + 1] != '#' && maze[y][x + 1] != '%' && maze[y][x + 1] != 'S' && !hasBadBranch(y, x+1)) {
steps[y][x + 1]++;
solve(x + 1, y, "east");
} else {
solve(x, y, "north");
}
} else if (facing.equals("west")) {
if (maze[y - 1][x] != '#' && maze[y - 1][x] != '%' && maze[y - 1][x] != 'S' && !hasBadBranch(y-1, x)) {
steps[y - 1][x]++;
solve(x, y - 1, "north");
} else if (maze[y][x - 1] != '#' && maze[y][x - 1] != '%' && maze[y][x - 1] != 'S'&& !hasBadBranch(y, x-1)) {
steps[y][x - 1]++;
solve(x - 1, y, "west");
} else {
solve(x, y, "south");
}
} else if (facing.equals("south")) {
if (maze[y][x - 1] != '#' && maze[y][x - 1] != '%' && maze[y][x - 1] != 'S' && !hasBadBranch(y, x-1)) {
steps[y][x - 1]++;
solve(x - 1, y, "west");
} else if (maze[y + 1][x] != '#' && maze[y + 1][x] != '%' && maze[y + 1][x] != 'S' && !hasBadBranch(y+1, x)) {
steps[y + 1][x]++;
solve(x, y + 1, "south");
} else {
solve(x, y, "east");
}
} else if (facing.equals("north")) {
if (maze[y][x + 1] != '#' && maze[y][x + 1] != '%' && maze[y][x + 1] != 'S' && !hasBadBranch(y, x+1)) {
steps[y][x + 1]++;
solve(x + 1, y, "east");
} else if (maze[y - 1][x] != '#' && maze[y - 1][x] != '%' && maze[y - 1][x] != 'S' && !hasBadBranch(y-1, x)) {
steps[y - 1][x]++;
solve(x, y - 1, "north");
} else {
solve(x, y, "west");
}
}
} else {
writeToFile();
System.out.println("Found the finish!");
currentTime = System.currentTimeMillis();
long endTime = currentTime - startTime;
long finalTime = endTime / 1000;
System.out.println("Final Time = " + finalTime);
}
}
public boolean hasBadBranch(int y, int x) {
//9999 will be used to tell character not to take that branch
if (steps[y][x] > 1) {
if (steps[y + 1][x] > 1) {
steps[y + 1][x] = 9999;
return true; //south
}
if (steps[y - 1][x] > 1) {
steps[y - 1][x] = 9999;
return true; //north
}
if (steps[y][x + 1] > 1) {
steps[y][x + 1] = 9999;
return true; //east
}
if (steps[y][x - 1] > 1) {
steps[y][x - 1] = 9999;
return true; //west
}
}
return false;
}
/**
* Opens a text file containing a maze and stores the data in the 2D char
* array maze[][].
*
* @param fname String value containing the file name of the maze to open.
*/
public void openMaze(String fname) {
String in = "";
int i = 0;
try {
Scanner sc = new Scanner(new File(fname));
while (sc.hasNext()) {
in = sc.nextLine();
in = trimWhitespace(in);
if (in.length() <= MAX_WIDTH && i < MAX_HEIGHT) {
for (int j = 0; j < in.length(); j++) {
if (in.charAt(j) == '#') { // if this spot is a wall, randomize the wall peice to display
if (random.nextInt(2) == 0) {
maze[i][j] = '#';
} else {
maze[i][j] = '%';
}
} else {
maze[i][j] = in.charAt(j);
}
}
} else {
System.out.println("Maximum maze size exceeded: (" + MAX_WIDTH + " x " + MAX_HEIGHT + ")!");
System.exit(1);
}
i++;
}
width = in.length();
height = i;
System.out.println("(" + width + " x " + height + ") maze opened.");
System.out.println();
sc.close();
} catch (FileNotFoundException e) {
System.err.println("File not found: " + e);
}
}
/**
* Removes white space from the supplied string and returns the trimmed
* String.
*
* @param s String value to strip white space from.
* @return String stripped of white space.
*/
public String trimWhitespace(String s) {
String newString = "";
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) != ' ') {
newString += s.charAt(i);
}
}
return newString;
}
/**
* Returns the sprite facing the direction supplied.
*
* @param facing String value containing 1 of 4 cardinal directions to make
* the sprite face.
* @return Image of the sprite facing the proper direction.
*/
private Image printGuy(String facing) {
if (facing.equals("south")) { // draw sprite facing south
if (step) {
step = false;
return south1.getImage();
} else {
step = true;
return south2.getImage();
}
} else if (facing.equals("north")) { // draw sprite facing north
if (step) {
step = false;
return north1.getImage();
} else {
step = true;
return north2.getImage();
}
} else if (facing.equals("east")) { // draw sprite facing east
if (step) {
step = false;
return east1.getImage();
} else {
step = true;
return east2.getImage();
}
} else if (facing.equals("west")) { // draw sprite facing west
if (step) {
step = false;
return west1.getImage();
} else {
step = true;
return west2.getImage();
}
}
return null;
}
/**
* Prints the Maze using sprites.
*
* @return BufferedImage rendition of the maze.
*/
public BufferedImage printMaze() {
BufferedImage mi = new BufferedImage(width * SPRITE_WIDTH, height * SPRITE_HEIGHT, BufferedImage.TYPE_INT_ARGB);
Graphics g2 = mi.createGraphics();
for (int i = 0; i < height; i++) {
for (int j = 0; j < width; j++) {
if (maze[i][j] == '#') { // draw wall
g2.drawImage(wall1.getImage(), j * SPRITE_WIDTH, i * SPRITE_HEIGHT, null, null);
} else if (maze[i][j] == '%') { // draw wall
g2.drawImage(wall2.getImage(), j * SPRITE_WIDTH, i * SPRITE_HEIGHT, null, null);
} else if (maze[i][j] == '.' || maze[i][j] == 'X') { // draw ground
g2.drawImage(ground.getImage(), j * SPRITE_WIDTH, i * SPRITE_HEIGHT, null, null);
} else if (maze[i][j] == 'F') { // draw finish
g2.drawImage(finish.getImage(), j * SPRITE_WIDTH, i * SPRITE_HEIGHT, null, null);
}
}
}
return mi;
}
public void writeToFile() throws FileNotFoundException {
PrintWriter printWriter = new PrintWriter("steps.txt");
for (int i = 0; i < width; i++) {
for (int j = 0; j < height; j++) {
printWriter.print(steps[i][j] + " ");
}
printWriter.println();
}
printWriter.close();
}
public void closingMethod() {
long endTime = currentTime - startTime;
long finalTime = endTime / 100;
System.exit(0);
}
private class TimerHandler implements ActionListener {
public void actionPerformed(ActionEvent e) {
timerFired = true;
}
}
private class WindowHandler extends WindowAdapter {
public void windowClosing(WindowEvent e) {
removeAll();
closingMethod();
System.exit(0);
}
}
}
source to share
Essentially, you've decided to solve the maze with DFS with a fixed exploration rule (right hand). The information you need to keep is the number of times you have stepped on the square. when you hit a dead end, you go back to the crossroads to try another branch.
So in the second solution, when you find an intersection with a score> 1, you should change the exploration rule to avoid branches with a score> 1 (1 means you never had to go back == the previous solution path, 2 (or more) means that you needed to come back after a dead end (or several)). Hope this made sense.
source to share