关于我家马不会走这件事
  • 板块P1443 马的遍历
  • 楼主Maysoul
  • 当前回复13
  • 已保存回复13
  • 发布时间2022/1/18 15:22
  • 上次更新2023/10/28 12:03:22
查看原帖
关于我家马不会走这件事
409774
Maysoul楼主2022/1/18 15:22

除了(x,y)都是-1,求大佬指正

#include<bits/stdc++.h>
using namespace std;
int read()
{
	int s=0,w=1;
	char ch=getchar();
	while(ch<'0'||ch>'9'){if(ch=='-'){w=-1;}ch=getchar();}
	while(ch>='0'&&ch<='9'){s=s*10+ch-'0';ch=getchar();}
	return s*w;
}
struct house{
	int x,y;
}q[3000];
int xx[8]={-1,-2,-2,-1,1,2,2,1};
int yy[8]={-2,-1,1,2,-2,-1,1,2};
int brd[500][500]={0};
bool vis[500][500];
int n,m,x,y;
void bfs()
{
	int h=0,t=1,step=0;
	q[0].x=x;q[0].y=y;
	while(h<t)
	{
		h++;
		step=brd[q[h].x][q[h].y]+1;
		for (int i=0;i<8;i++)
		{
			int sx=q[h].x+xx[i];
			int sy=q[h].y+yy[i];
			if(x+xx[i]>=1&&x+xx[i]<n&&y+yy[i]>=1&&y+yy[i]<m&&vis[x+xx[i]][y+yy[i]]==0)
			{
				t++;
				q[t].x=sx;
				q[t].y=sy;
				vis[sx][sy]=true;
				brd[q[t].x][q[t].y]=step;
			}
		}
	}
}
int main()
{
	n=read(),m=read(),x=read(),y=read();
	memset(vis,false,sizeof vis);
	vis[x][y]=true;
	brd[x][y]=0;
	bfs();
	for (int i=0;i<n;i++)
	{
		for (int j=0;j<m;j++)
		{
			if(!vis[i][j])
			{
				cout<<"-1"<<" ";
			}
			else
			{
				cout<<brd[i][j]<<" ";
			}
		}
		cout<<endl;
	}
	return 0;
}
2022/1/18 15:22
加载中...