Qhy2023 @ 2024-11-19 20:52:48
哪里错了?
#include<bits/stdc++.h>
using namespace std;
const int N=405;
struct point{
int x,y,step;
};
int a[N][N];
int n,m,x,y;
int dx[8]={-2,-1,1,2,2,1,-1,-2},dy[8]={1,2,2,1,-1,-2,-2,-1};
void bfs(){
queue<point> qu;
a[x][y]=0;
qu.push({x,y,0});
while(!qu.empty()){
point now=qu.front();
qu.pop();
for(int i=0;i<=8;i++){
int _x,_y;
_x=now.x+dx[i],_y=now.y+dy[i];
if(_x>=1&&_x<=n&&_y>=1&&_y<=m&&a[_x][_y]==-1){
a[_x][_y]=now.step+1;
qu.push({_x,_y,a[_x][_y]});
}
}
}
}
int main(){
cin>>n>>m>>x>>y;
memset(a,-1,sizeof(a));
bfs();
for(int i=1;i<=n;i++){
for(int j=1;j<=n;j++) cout<<setw(3)<<fixed<<left<<a[i][j];
cout<<endl;
}
return 0;
}
by pengchengen @ 2024-11-28 20:07:16
输出错了 RE应为你bfs的for从0到8了,应该为i<8
#include<bits/stdc++.h>
using namespace std;
const int N=405;
struct point{
int x,y,step;
};
int a[N][N];
int n,m,x,y;
int dx[8]={-2,-1,1,2,2,1,-1,-2},dy[8]={1,2,2,1,-1,-2,-2,-1};
void bfs(){
queue<point> qu;
a[x][y]=0;
qu.push({x,y,0});
while(!qu.empty()){
point now=qu.front();
qu.pop();
for(int i=0;i<8;i++){
int _x,_y;
_x=now.x+dx[i],_y=now.y+dy[i];
if(_x>=1&&_x<=n&&_y>=1&&_y<=m&&a[_x][_y]==-1){
a[_x][_y]=now.step+1;
qu.push({_x,_y,a[_x][_y]});
}
}
}
}
int main(){
cin>>n>>m>>x>>y;
memset(a,-1,sizeof(a));
bfs();
for(int i=1;i<=n;i++){
for(int j=1;j<=m;j++) cout<<setw(5)<<fixed<<left<<a[i][j];
cout<<endl;
}
return 0;
}