90分求助
查看原帖
90分求助
1122180
封禁用户楼主2024/10/1 16:13

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;
}
2024/10/1 16:13
加载中...