简体   繁体   中英

Backtracking maze

I'm trying to write a maze solver using backtracking. It should see whether it's possible to solve a given puzzle from the starting point S to the end point E. The pseudo code can be seen in this link here. My implementation looks like this:

const int N = 8; // global var

bool exploreMaze(char maze[][N], int x, int y)
{
    if(y >= 8 || y < 0 || x >= 7 || x < 0) // null char at end of each 1d array 
        return false;
    if(maze[x][y] == '*')
        return false;
    if(maze[x][y] == 'E')
        return true;
    maze[x][y] = '*'; // set grid to '*' as to not loop infinitely
    if(exploreMaze(maze,  x + 1, y))
    {
        cout << "up" << ", ";
        return true;
    }
    if(exploreMaze(maze,  x - 1, y))
    {
        cout << "down" << ", ";
        return true;
    }
    if(exploreMaze(maze, x, y - 1))
    {
        cout << "left" << ", ";
        return true;
    }
    if(exploreMaze(maze, x, y + 1))
    {
        cout << "right" << ", ";
        return true;
    }

    return false;
}

bool isMazeSolvable(char maze[][N])
{
    int startX = -1, startY = -1;

    for(int i = 0; i < N; i++)
    {
        for(int j = 0; j < N; j++)
        {
            if(maze[i][j] == 'S')
                startX = i;
                startY = j;
        }
    }
    if(startX == -1)
        return false;

    return exploreMaze(maze, startX, startY);

}

int main()
{
    char maze[N][N] = {"*******", " S     ", "*******", "  E    ", "*******",         
    "*******", "*******", "*******"};
    cout << isMazeSolvable(maze);
    return 0;
}

The array that I'm testing in main should definitely have no solution, but somehow I'm getting 1(true) as the output. Any ideas?

Your maze '*' is only initialized out in the Y direction by 7 characters, but your maze walker checks out to 8 character. This allows it to walk around the end of your walls.

I added a quick maze print function and changed the exploreMaze to put '.' where it walks. Giving the following output:

Initial maze:
*******
 S
*******
  E
*******
*******
*******
*******

left, left, left, left, left, up, up, right, right, right, right, right, right,

1

After explore:
*******
 .......
*******.
  E.....
*******
*******
*******
*******

Soluton: Either change the initializer to use 8 character walls, or change the exploreMaze function to only look 7 characters in the Y direction.

Also note: You are not doing the "backtracking" part of the maze solver, because you mark where you have been but don't clean off your path on your way out of the recursion. Add

maze[x][y] = ' '; // Clear the grid so we can try this spot again in another recursion

to the end of your exploreMaze function

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM