Milas
Milas

Reputation: 347

Maze algorithm path finder

I am trying to find the path of a maze, below is the code, it suppose to goes inside the recursiveSolve loop but it keep exiting, after second if condition what i am doing wrong here can someone help me please? im setting Washere and correctpath array as false by default.

recursiveSolve(0, 0);

public static int[,] maze = {{0, 0, 0, 0, 0, 1},
                             {1, 1, 0, 0, 0, 1},
                             {0, 0, 0, 1, 0, 0},
                             {0, 1, 1, 0, 0, 1},
                             {0, 1, 0, 0, 1, 0},
                             {0, 1, 0, 0, 0, 1}};

public static Boolean recursiveSolve(int row, int col) {
    Boolean[,] wasHere = new Boolean[6, 6];
    Boolean[,] correctPath = new Boolean[6, 6]; // The solution to the maze

    if (maze[row, col] == 1 || wasHere[row, col]) {
        return false;
    }
    else if (row == 0 || row == 6 - 1 || col == 0 || col ==6 - 1) {
        correctPath[row, col] = true;
        return true;
    }
    else {
        wasHere[row, col] = true;
        if (recursiveSolve(row - 1, col) || recursiveSolve(row + 1, col) ||
                                            recursiveSolve(row, col - 1) || 
                                            recursiveSolve(row, col +1)) {
            correctPath[row, col] = true;
            return true; // successfully escaped; this square is on path
        }
        else {
            return false;
        }
    }
} 

Upvotes: 0

Views: 945

Answers (2)

larslovlie
larslovlie

Reputation: 189

If you're actually doing path finding and this is not an excercise which requires this particular solution, then you might also want to look into the A* algorithm which is probably more efficient and robust.

Wikipedia

Upvotes: 0

MichaelCMS
MichaelCMS

Reputation: 4763

Your wasHere and correctPath arrays are local to the recursiveSolve function, which means each time you enter in this function, the arrays will be inited to false (or random value).

First of all try to make these arrays static as well, and see if that solves your problem with the always false.

Also, you should start your search from somewhere inside the maze instead of from an edge (0,0 means you already exiting the maze). If you want to start from 0,0 ,mark that as a starting point, and don't allow it as a valid solution.

Upvotes: 1

Related Questions