bfs悬关求助

P1443 马的遍历

注意地图是 $n\times m$ 的,不是 $n\times n$ 的,遍历时 $y$ 对应的边界为 $m$。 ``` #include<iostream> #include<queue> #include<iomanip> using namespace std; int n,m,x,y; int mp[500][500]={0}; //地图 bool vis[500][500]; //判断有没有走过该点 int dirx[]={2,1,-1,-2,-2,-1,1,2}; //马走的8个方向 int diry[]={1,2,2,1,-1,-2,-2,-1}; struct AXI{ int x,y; }ax; queue<AXI> qu; bool judge(int x,int y){ if(x<1||y<1||x>n||y>m){ //超出地图,y对应的应为m return false; } if(vis[x][y]==true){ //已经走过该点 return false; } return true; } void BFS(int x,int y){ ax.x=x; ax.y=y; qu.push(ax); int step=1; //第几次搜索 while(!qu.empty()){ int len=qu.size(); while(len--){ for(int i=0;i<8;i++){ int tx=qu.front().x+dirx[i]; int ty=qu.front().y+diry[i]; if(judge(tx,ty)){ //判断有无超出边界,有无走过该点 ax.x=tx; ax.y=ty; qu.push(ax); mp[tx][ty]=step; vis[tx][ty]=true; } } qu.pop(); } step++; } } int main(){ cin>>n>>m>>x>>y; vis[x][y]=true; //初始化起始点 mp[x][y]=0; BFS(x,y); for(int i=1;i<=n;i++){ //输出 for(int j=1;j<=m;j++){//这里是m,不是n if(vis[i][j]==false){ //马没走过的点输出-1 cout<<left<<setw(5)<<-1; }else{ cout<<left<<setw(5)<<mp[i][j]; } } cout<<endl; } return 0; } ```
by Wilderness_114514 @ 2024-03-29 13:50:24


@[spessert](/user/881317) $judge$ 写错了,应该是 $y>m$。
by lqsy002 @ 2024-03-29 13:55:44


@[Wilderness_114514](/user/816495) 感谢感谢!!已关
by spessert @ 2024-03-29 14:10:22


@[lqsy002](/user/1216630) 感谢!!关注了
by spessert @ 2024-03-29 14:10:42


|