Hi guys. I've been doing pretty good with my programming so its been awhile since my last post, but as the title suggests I am stuck on traversing my maze using recursion. I have a 2D array that is given a set value to represent my maze. My constructor creates a 2D array that is sized by given row and column values, and then the actual values themselves are passed after that. It appears that the problem lies when I come across the character that's supposed to represent the walls of the maze, which is a *. It gives me the following error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5 at recursivemaze.Maze.traverse(Maze.java:41) at recursivemaze.Maze.traverse(Maze.java:52) at recursivemaze.Maze.traverse(Maze.java:52) at recursivemaze.Maze.traverse(Maze.java:52) at recursivemaze.Maze.traverse(Maze.java:52) at recursivemaze.Maze.traverse(Maze.java:51) at recursivemaze.Maze.traverse(Maze.java:51) at recursivemaze.RecursiveMaze.main(RecursiveMaze.java:26) Java Result: 1
I'm not sure what the problem is, because my code is supposed to return nothing when it comes across a * and keep continuing the recursive method calls until it reaches the last possible part of the maze that it can travel, all the while placing a 'P' in areas where it has traveled. Any help would be appreciated in solving this. My code is as followed:
public class Maze { private char[][] primeMaze = null; private int rows = 0; private int columns = 0; private final char PATH = 'P'; private int total = 0; public Maze(){ } public Maze(int x, int y){ rows = x; columns = y; primeMaze = new char[x][y]; } public int getDimensions(){ return (rows * columns); } public void fillMaze(char[][] m){ for (int i = 0; i < primeMaze.length; i++){ for (int j = 0; j < primeMaze[i].length; j++){ primeMaze[i][j] = m[i][j]; } } } public void traverse(int r, int c){ if (primeMaze[r][c] == '*'){ return; ****This is the source of the error**** } if (primeMaze[r][c] == PATH){ return; } primeMaze[r][c] = PATH; traverse(r + 1, c); traverse(r, c + 1); traverse(r - 1, c); traverse(r, c - 1); primeMaze[r][c] = ' '; return; } public String toString(){ String answer = null; for (int i = 0; i < rows; i++){ for (int j = 0; j < columns; j++){ answer += primeMaze[i][j] + " "; } answer += "\n"; } return answer; } }
public class RecursiveMaze { /** * @param args the command line arguments */ public static void main(String[] args) { char[][] test = new char[][]{{'*', '*', '*', '*', '*'}, {'*', ' ', ' ', '*', '*'}, {'*', ' ', '*', '*', '*'}, {'*', ' ', ' ', ' ', ' '}, {'*', '*', '*', '*', '*'}}; Maze m = new Maze(5, 5); m.fillMaze(test); m.traverse(1, 1); System.out.println(m.toString()); } }