Search code examples
javarecursionrecursive-backtracking

How do I find the solution of a particular maze using recursive bactracking (Java)?


I am trying to write a program that solves a maze recursively. When a step has been made, an 'x' character is placed at that position in the maze and the maze is printed, if the maze reaches a dead end it backtracks its last recursive step by removing the 'x' from that position.

When run, the program always stops at the first step; it does not solve the maze completely

I have tried:

-Hardcoding each consecutive step to take to avoid a wall in the maze (but this defeats the purpose of using recursion)

-Starting the first step to take randomly (but this results in ArrayIndexOutOfBoundsException)

import java.util.Random;

public class MazeTraversalWithRecursiveBacktracking
{

  private static Random random = new Random();
  public static void main(String args[])
  {

    char [][] maze = {{'#', '#', '#', '#', '#', '#','#', '#', '#', '#', '#', '#'}, 
                         {'#', '.', '.', '.', '#', '.','.', '.', '.', '.', '.', '#'}, 
                         {'.', '.', '#', '.', '#', '.','#', '#', '#', '#', '.', '#'}, 
                         {'#', '#', '#', '.', '#', '.','.', '.', '.', '#', '.', '#'}, 
                         {'#', '.', '.', '.', '.', '#','#', '#', '.', '#', '.', '.'}, 
                         {'#', '#', '#', '#', '.', '#','.', '#', '.', '#', '.', '#'}, 
                         {'#', '.', '.', '#', '.', '#','.', '#', '.', '#', '.', '#'}, 
                         {'#', '#', '.', '#', '.', '#','.', '#', '.', '#', '.', '#'}, 
                         {'#', '.', '.', '.', '.', '.','.', '.', '.', '#', '.', '#'}, 
                         {'#', '#', '#', '#', '#', '#','.', '#', '#', '#', '.', '#'}, 
                         {'#', '.', '.', '.', '.', '.','.', '#', '.', '.', '.', '#'}, 
                         {'#', '#', '#', '#', '#', '#','#', '#', '#', '#', '#', '#'}};


    printMaze(maze);
    mazeTraversal(maze, 2, 0);
  }

  public static void mazeTraversal(char [][] maze, int currX, int currY)
{
      int choice = -1;
try
{
maze[currX][currY] = 'x';
printMaze(maze);
boolean chosen = false;

if ((currX == 4) && (currY == 11)) //end of the maze
{
 System.out.println("Maze completed");
 return;
}


while(!chosen)
{
choice = 1;
//System.out.println("Choice "+choice);
if (choice == 0)
{
    if (maze[currX-1][currY] == '.')//up
{
    System.out.println("Chose up");
 chosen = true;
}
else
    choice = random.nextInt(4);
}
else if (choice == 1)
{
if (maze[currX][currY+1] == '.')//right
{
    System.out.println("Chose right");
 chosen = true;
}
else
    choice = random.nextInt(4);
}
else if (choice == 2)
{
    if (maze[currX+1][currY] == '.')//down
{
    System.out.println("Chose down");
 chosen = true;
}
else
    choice = random.nextInt(4);
}
else if (choice == 3)
{
    if (maze[currX][currY-1] == '.')//left
{
    System.out.println("Chose left");
 chosen = true;
}
else
    choice = random.nextInt(4);
}
else
{
    System.out.println("Haven't chosen");
    choice = random.nextInt(4);
}
//System.out.println(choice+" "+chosen);
}
System.out.println(choice+" "+chosen);
if (choice == 0)
 mazeTraversal(maze,currX-1,currY);
else if (choice == 1)
 mazeTraversal(maze,currX,currY+1);
else if (choice == 2) 
 mazeTraversal(maze,currX+1,currY);
else if (choice == 3)
 mazeTraversal(maze,currX,currY-1);
else //backup
{
  recursiveBacktrack(maze, currX, currY);
}
}
catch(ArrayIndexOutOfBoundsException ex)
{
    ex.printStackTrace();
    System.out.println("Maze finished with choice = "+choice);
}
}

public static void recursiveBacktrack(char [][]maze, int currX,  int currY)
{
maze[currX][currY] = ' ';
}

  public static void printMaze(char maze[][])
  {
    for(int i = 0; i < 12; ++i)
    {
      for(int j = 0; j < 12; ++j)
      {
         System.out.print(maze[i][j]+" ");
      }
      System.out.println();
    }
    System.out.println();
    System.out.println();
  }
}

Expected Result: The expected result is for the maze to be solved recursively showing each attempt by reprinting the entire maze after each recursive step. '#' is a wall, '.' is a free space and 'x' is a spaced that has been occupied.

Actual Result: The actual result I get, as said previously is just the first recursion step after which the program loops indefinitely.

Error Message: Occasionally, I get the error message ArrayIndexOutOfBoundsException: -1


Solution

  • Let's first see how isValidDirection and isSolution should work like:

    public boolean isValidDirection(x, y) {
        return ((x < maze.length) &&
                (x >= 0) &&
                (y < maze[x].length) &&
                (y >= 0) &&
                (maxe[x][y] == '.'));
    }
    
    public boolean isSolution(x, y) {
        return isValidDirection(x, y) && (((x % maze.length) - 1 == 0) || ((y % maze[x].length) - 1 == 0));
    }
    

    Let's implement the maze runner:

    public boolean mazeRunner(x, y) {
        if (!isValidDirection) {
            //TODO: output the attempt
        }
        maze[x][y] = 'x';
        //add (x,y) to current attempt
        //we need to count attempt length 
        if (isSolution(x, y)) {
            //TODO: output the successful attempt
        } else if ((
            (mazeRunner(x - 1, y)) ||
            (mazeRunner(x + 1, y)) ||
            (mazeRunner(x, y - 1)) ||
            (mazeRunner(x, y + 1))
            ) == false) {
            //TODO: Output the current failed attempt
        }
        maze[x][y] = '.';
        //TODO: remove (x, y) from the current attempt
    }
    
    public void startMazeRunning(char[][] maze, x, y) {
        this.maze = maze;
    }
    

    Of course, you will need to ensure that all the members that are needed are defined and properly initialized.