简体   繁体   English

如何解决迷宫程序中的递归算法堆栈溢出?

[英]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代表墙, 0代表可以走的路, $代表终点。 (1,2) is the starting point. (1,2) 是起点。

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

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.有这样的要求是一种“好的”,但我更喜欢边界检查。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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