Search code examples
cstack-overflow

How to solve the recursive algorithm stack overflow in a maze program?


I have a simple program to solve the maze. But an error is reported: stack overflow. How can I solve the stack overflow?

In my code, 1 represents the wall, 0 represents the path that can be taken, and $ represents the end. (1,2) is the starting point.

This is my code:

#include<stdio.h>
#include<windows.h>

void ShowMaze(char szMaze[][24],int nCount)
{
    
    for(int i=0;i<nCount;i++)
    {
        printf("%s\r\n",szMaze[i]);
    }
}

void Maze(char szMaze[][24],int x,int y)
{
    if(szMaze[x][y]=='$')
    {
        printf("Congratulations!\r\n");
        system("pause");
        exit(0);
    }

    if (szMaze[x+1][y]=='$'||szMaze[x+1][y]=='0')
    {
        Maze(szMaze,x+1,y);
    }
    if (szMaze[x][y+1]=='$'||szMaze[x][y+1]=='0')
    {
        Maze(szMaze,x,y+1);
    }
    if (szMaze[x-1][y]=='$'||szMaze[x-1][y]=='0')
    {
        Maze(szMaze,x-1,y);
    }
    if (szMaze[x][y-1]=='$'||szMaze[x][y-1]=='0')
    {
        Maze(szMaze,x,y-1);
    }
    
    return;
}

int main()
{
    char szMaze[][24]={
    "11111111111111111111111",
    "10111111111111111111111",
    "10000000001111111111011",
    "11111111011111100001011",
    "11111111011111101111011",
    "11111111000000000001$11",
    "11111111011111101111011",
    "11111111011111100000001",
    "11111111111111111111111"
    };
    int nRow=sizeof(szMaze)/sizeof(szMaze[0]);
    ShowMaze(szMaze,nRow);

    Maze(szMaze,1,2);
    
    system("pause");
    return 0

Solution

  • To avoid endless loops you need to mark positions that have already been visited.

    Something like:

    szMaze[x][y]='2'; // mark position as visited
    if (szMaze[x+1][y]=='$'||szMaze[x+1][y]=='0')
    {
        Maze(szMaze,x+1,y);
    }
    if (szMaze[x][y+1]=='$'||szMaze[x][y+1]=='0')
    {
        Maze(szMaze,x,y+1);
    }
    if (szMaze[x-1][y]=='$'||szMaze[x-1][y]=='0')
    {
        Maze(szMaze,x-1,y);
    }
    if (szMaze[x][y-1]=='$'||szMaze[x][y-1]=='0')
    {
        Maze(szMaze,x,y-1);
    }
    szMaze[x][y]='0'; // release position
    

    and don't start in the wall! Start like:

    Maze(szMaze,1,2); ---->   Maze(szMaze,1,1);
    

    Note

    Your code don't do any boundary checking. Therefore it will only work when the maze has walls at all boundaries. Having such a requirement is kind of "okay" but I would prefer boundary checking instead.