C++BFS死循环问题

洛谷原题:https://www.luogu.com.cn/problem/P1443
第一次写BFS,不知道为啥会死循环
我的代码:

#include<cstdio>
#include<iostream>
#include<algorithm>
#include<queue>
using namespace std;

int n,m,x,y;
int map[405][405]={-1};
int dx[]={-2,-2,-1,-1,1,1,2,2};
int dy[]={1,-1,2,-2,2,-2,1,-1};


struct node{
    int x,y,step;
}now,nextt;

void bfs(int x,int y){
    queue<node>q;
    map[x][y]=0;
    now.x=x;now.y=y;now.step=0;
    q.push(now);//初始化
    while(!q.empty()){
        now=q.front();q.pop();
        for(int i=0;i<8;i++){//遍历X个方向 
            int xx=now.x+dx[i];
            int yy=now.y+dy[i];
            if(xx>=1&&xx<=n&&yy>=1&&yy<=m&&map[xx][yy]==-1) {
                nextt.x=xx;nextt.y=yy;nextt.step=now.step+1;
                map[xx][yy]=nextt.step;
                return;
                q.push(nextt);
            }
        }
    } 
}

int main(){
    cin>>n>>m>>x>>y;
    bfs(x,y);
    for(int i=1;i<=n;i++)for(int j=1;i<=m;j++)printf("%5d",map[i][j]);
    return 0;
}

你这个代码问题挺大(抱歉
1.死循环:这是输出的问题
应该为

  for(int i=1;i<=n;i++)
    {
        for(int j=1;j<=m;j++)
        {
            printf("%5d",map[i][j]);
        }
        printf("\n");
    }

2.bfs:
问题很大。
建议看一下这篇文章:https://blog.csdn.net/aliyonghang/article/details/128724989?spm=1001.2014.3001.5502

最后
给你浅浅修改了一下,可以通过~

#include<cstdio>
#include<iostream>
#include<algorithm>
#include<queue>
using namespace std;
 
int n,m,x,y;
int map[405][405];
int dx[]={-2,-2,-1,-1,1,1,2,2};
int dy[]={1,-1,2,-2,2,-2,1,-1};
 
 
struct node{
    int x,y,step;
}now,nextt;
 
void bfs(int x,int y){
    queue<node>q;
    map[x][y]=0;
    now.x=x;now.y=y;now.step=0;
    q.push(now);//初始化
    while(!q.empty())
    {
        for(int i=0;i<8;i++)
        {//遍历X个方向 
            now=q.front();
            int xx=now.x+dx[i];
            int yy=now.y+dy[i];
            if(xx>=1&&xx<=n&&yy>=1&&yy<=m&&map[xx][yy]==-1)
            {
                nextt.x=xx;
                nextt.y=yy;
                nextt.step=now.step+1;
                map[xx][yy]=nextt.step;
             //   return;
                q.push(nextt);
            }
        }
        q.pop();
    } 
}
 
int main(){
    cin>>n>>m>>x>>y;
    for(int i=1;i<=n;i++)
    {
        for(int j=1;j<=m;j++)
        {
            map[i][j]=-1;
        }
    }
    bfs(x,y);
    for(int i=1;i<=n;i++)
    {
        for(int j=1;j<=m;j++)
        {
            printf("%5d",map[i][j]);
        }
        printf("\n");
    }
    return 0;
}

还不懂的话问我,有时间一定会解答

不知道你这个问题是否已经解决, 如果还没有解决的话:

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