40求调
查看原帖
40求调
780505
x1489631649楼主2024/1/4 19:21
#include<bits/stdc++.h>
using namespace std;
int n,m,x,y;
int f[500][500],vis[500][500];
struct node{
	int x,y,step;
}q[10000];
int dx[10]={2,2,-2,-2,1,-1,1,-1};
int dy[10]={-1,1,-1,1,2,2,-2,-2};
void bfs()
{
	int t,h;
	t=h=1;
	q[h].x=x;
	q[h].y=y;
	vis[x][y]=1;
	while(h<=t)
	{
		for(int i=0;i<8;i++)
		{
			int nx=q[h].x+dx[i];
			int ny=q[h].y+dy[i];
			if(nx>0&&nx<=n&&ny>0&&ny<=m&&vis[nx][ny]==0)
			{
				t++;
				q[t].x=nx;
				q[t].y=ny;
				q[t].step=q[h].step+1;
				vis[nx][ny]=1;
				f[nx][ny]=q[t].step;
			}
		}
		h++;
	}
}
int main()
{
    cin>>n>>m>>x>>y;
	memset(f,-1,sizeof(f));
	f[x][y]=0;
    bfs(); 
    for(int i=1;i<=n;i++)
    {
    	for(int j=1;j<=m;j++)
    	{
    		if(i==y&&j==x)
    			cout<<left<<setw(5)<<0;
    		else cout<<left<<setw(5)<<f[i][j];
		}
		cout<<endl;
	}
    return 0;
}
2024/1/4 19:21
加载中...