qrz0226 @ 2024-10-01 16:13:03
90分求助 代码如下
#include<bits/stdc++.h>
using namespace std;
const int N=410;
struct node{
int x,y;
};
int n,m,x,y;
int vis[N][N],ans[N][N];
const int dx[8]={-1,-2,-2,-1,1,2,2,1};
const int dy[8]={2,1,-1,-2,2,1,-1,-2};
void bfs(node s) //x行y列
{
queue<node> q;
q.push(s);
int cnt=0;
while(!q.empty())
{
node tmp=q.front();
q.pop();
int sx=tmp.x,sy=tmp.y;
for(int i=0;i<8;i++)
{
int xx=sx+dx[i],yy=sy+dy[i];
if(!vis[xx][yy] && xx>0 && yy>0 && xx<=n && yy<=m){
//cout<<xx<<" "<<yy<<endl;
vis[xx][yy]=1;
ans[xx][yy]=ans[sx][sy]+1;
node t;
t.x=xx,t.y=yy;
q.push(t);
}
}
}
}
int main()
{
cin>>n>>m>>x>>y;
vis[x][y]=1;
ans[x][y]=0;
node t;
t.x=x,t.y=y;
bfs(t);
for(int i=1;i<=n;i++)
{
for(int j=1;j<=m;j++)
{
if(ans[i][j]==0 && (i!=x && j!=y)){
cout<<"-1 ";
continue;
}
cout<<ans[i][j]<<" ";
}
cout<<endl;
}
return 0;
}
by Luo_Saisei @ 2024-10-01 16:20:14
@qrz0226 ans数组初始化为-1
by Luo_Saisei @ 2024-10-01 16:20:53
@qrz0226
#include<bits/stdc++.h>
using namespace std;
const int N=410;
struct node{
int x,y;
};
int n,m,x,y;
int vis[N][N],ans[N][N];
const int dx[8]={-1,-2,-2,-1,1,2,2,1};
const int dy[8]={2,1,-1,-2,2,1,-1,-2};
void bfs(node s) //x行y列
{
queue<node> q;
q.push(s);
int cnt=0;
while(!q.empty())
{
node tmp=q.front();
q.pop();
int sx=tmp.x,sy=tmp.y;
for(int i=0;i<8;i++)
{
int xx=sx+dx[i],yy=sy+dy[i];
if(!vis[xx][yy] && xx>0 && yy>0 && xx<=n && yy<=m){
//cout<<xx<<" "<<yy<<endl;
vis[xx][yy]=1;
ans[xx][yy]=ans[sx][sy]+1;
node t;
t.x=xx,t.y=yy;
q.push(t);
}
}
}
}
int main()
{
cin>>n>>m>>x>>y;
memset(ans,-1,sizeof(ans));
vis[x][y]=1;
ans[x][y]=0;
node t;
t.x=x,t.y=y;
bfs(t);
for(int i=1;i<=n;i++)
{
for(int j=1;j<=m;j++)
{
printf("%-5d",ans[i][j]);
}
cout<<endl;
}
return 0;
}
by qrz0226 @ 2024-10-01 16:26:39
@gcomplex 谢谢奆佬