Вопрос

I'm trying to solve a problem which uses a 2D array, the problem of a rat in a maze.

While checking the conditions trying to compile, it finds an Array index out of bounds exception... how can I check the values so it doesn't go out of the array bounds?

static void solveMaze(){

    int nSteps = 0; // Number of steps.
    int x = 0; int y = 0; // Starting point.

    boolean mazeCompleted = false;

    while (!mazeCompleted){

        if(x == maze.mazeMatrix.length && y == maze.mazeMatrix.length)
            mazeCompleted = true;

        else if(maze.mazeMatrix[x+1][y] == 0){ // Move right.
            maze.mazeMatrix[x+1][y] = 2;
            x++; nSteps++;
        }

        else if(maze.mazeMatrix[x-1][y] == 0){ // Move left.
            maze.mazeMatrix[x-1][y] = 2;
            x--; nSteps++;
        }

        else if(maze.mazeMatrix[x][y+1] == 0){ // Move down.
            maze.mazeMatrix[x][y+1] = 2;
            y++; nSteps++;
        }

        else if(maze.mazeMatrix[x][y-1] == 0){ // Move up.
            maze.mazeMatrix[x][y-1] = 2;
            y--; nSteps++;
        }

    }

    maze.printMatrix();
    System.out.println("Maze COMPLETE! - With a total of " + nSteps + " steps.");

}

Tried before with two "for" loops to prevent the out of bounds but I just can't go diagonal in this problem.

Это было полезно?

Решение

You have a pretty crucial bug in your program. You will never reach the end of the maze!

if(x == maze.mazeMatrix.length && y == maze.mazeMatrix.length)

references indices that are out of bounds! It should be

if(x == maze.mazeMatrix.length - 1 && y == maze.mazeMatrix.length - 1)

You also need to check to see whether you can & should move before you try to move there. I.E. :

while (!mazeCompleted){

boolean moveRight = (x + 1 < mazeMatrix.length && maze.mazeMatrix[x+1][y] == 0 ? true : false);
boolean moveLeft = (x - 1 >= 0 && maze.mazeMatrix[x-1][y] == 0 ? true : false);
boolean moveUp = (y + 1 < mazeMatrix[x].length && maze.mazeMatrix[x][y+1] == 0 ? true : false);
boolean moveDown = (y - 1 >= 0 && maze.mazeMatrix[x][y-1] == 0 ? true : false);

And:

else if(moveRight) { // Move right.
        maze.mazeMatrix[x+1][y] = 2;
        x++; nSteps++;
}

etc. Although it does seem like this is something that should be solved recursively, as if there are any loops in the maze you will end up getting stuck and infinite looping.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top