Home > other >  Maze solver gets stuck in a loop (Stack overflow error)
Maze solver gets stuck in a loop (Stack overflow error)

Time:03-16

My recursive solver gets stuck at a dead end and can't turn around, causing a stack overflow error. Where am I going wrong?

solI is a public array. x2 and y2 are public solution coordinates.

0-wall
1-open path
2-tried
3-solution

RECURSIVE SOLVER

public static boolean traverse(int x1, int y1) {
    boolean done = false;
    count  ;
    if ((count < 100) && (x1 >= 0) && (x1 < solI.length) && (y1 >= 0) && (y1 < solI.length) && (solI[x1][y1] == 1)) {
        solI[x1][x1] = 2;
        if ((x1 == x2) && (y1 == y2)) {
            done = true;
        } else {
            if (!done) { //up
                done = traverse(x1 - 1, y1);
            }
            if (!done) {//left{
                done = traverse(x1, y1 - 1);
            }
            if (!done) {//down{
                done = traverse(x1   1, y1);
            }
            if (!done) {//right
                done = traverse(x1, y1   1);
            }
        }
        if (done) solI[x1][y1] = 3;

    }
    return done;
}

CodePudding user response:

The problem is in line 5 of your code. This solI[x1][x1] = 2; should be changed to this solI[x1][y1] = 2;. Also forget about the count. Having max count = 100 would cause problem in matrices with dimensions more than 10 * 10.

  • Related