c++迷宫出口,输出结果不对,找不出问题

c++迷宫出口,输出结果不对,找不出问题,麻烦帮忙看一下

#include<bits/stdc++.h>
using namespace std;
int a[101][101],fx[5]={0,0,1,0,-1},fy[5]={0,1,0,-1,0};
int ax,ay,bx,by,i,j,n,tx,ty; 
void f1(int x,int y)
{
    a[x][y]=1;
    for (i=1;i<=4;i++)
    {
        tx=x+fx[i];
        ty=y+fy[i];
        if (tx>=1&&tx<=n&&ty>=1&&ty<=n&&a[tx][ty]==0)
        {
            if (tx==bx&&ty==by)
            {
                cout<<"YES";
                exit(0);    
            } 
            else
            {
                f1(tx,ty);
            }
        }
    }
}  
int main()
{
    cin>>n;
    for (i=1;i<=n;i++)
    {
        for (j=1;j<=n;j++)
        {
            cin>>a[i][j];        
        }
    }
    cin>>ax>>ay>>bx>>by;
    if (a[ax][ay]==1)
    {
        cout<<"NO";
        exit(0);
    }
    f1(ax,ay);
    cout<<"NO";
    return 0;
}

【以下回答由 GPT 生成】

问题出在代码中的递归函数f1中,当找到目标点时,程序立即输出"YES"并退出,但并没有返回到上一层的递归调用。因此,当程序继续执行时,会继续输出"NO"。

为了解决这个问题,可以将目标点找到后的处理逻辑改为将函数的返回值设为true,并在递归调用上一层时返回该值。这样,在上一层递归调用中,如果返回值为true,则输出"YES",否则输出"NO"。

同时,还可以进行代码优化,避免重复计算和使用全局变量。具体优化方案如下:

#include<bits/stdc++.h>
using namespace std;

bool f1(vector<vector<int>>& maze, int ax, int ay, int bx, int by)
{
    int n = maze.size();
    if(ax<0 || ax>=n || ay<0 || ay>=n || maze[ax][ay]==1) {
        return false;
    }
    if(ax == bx && ay == by) {
        return true;
    }
    maze[ax][ay] = 1;
    int dx[4] = {0, 0, 1, -1};
    int dy[4] = {1, -1, 0, 0};
    for(int i=0; i<4; i++) {
        int tx = ax + dx[i];
        int ty = ay + dy[i];
        if(f1(maze, tx, ty, bx, by)) {
            return true;
        }
    }
    return false;
}

int main()
{
    int n;
    cin>>n;
    vector<vector<int>> maze(n, vector<int>(n));
    for(int i=0; i<n; i++) {
        for(int j=0; j<n; j++) {
            cin>>maze[i][j];
        }
    }
    int ax, ay, bx, by;
    cin>>ax>>ay>>bx>>by;
    if (f1(maze, ax, ay, bx, by)) {
        cout<<"YES";
    }
    else {
        cout<<"NO";
    }
    return 0;
}

这样的代码既解决了输出结果错误的问题,又进行了代码优化,使用了更好的变量命名和合理的函数返回值。



【相关推荐】



如果你已经解决了该问题, 非常希望你能够分享一下解决方案, 写成博客, 将相关链接放在评论区, 以帮助更多的人 ^-^

在读取迷宫输入时,将0和1直接存储在标记数组a中,而不是先存储在a中再进行标记。