【题解】洛谷P1443 马的遍历

1.注意输出格式 printf("-5d")代表左对齐,空5格。

2.team数组要开的大点。。否则会WA或者RE一些点。

3.结构体来存team数组,最后要判断到不了输出-1

好像也没啥了。。。

#include<cstdio>
#include<iostream>
#include<cstring>
#include<cstdlib>
#include<algorithm>
#include<iomanip>
using namespace std;
const int maxn=10010;
const int dx[8]={1,2,2,1,-1,-2,-2,-1};
const int dy[8]={2,1,-1,-2,-2,-1,1,2};
int n,m,x,y;
struct H
{
	int x,y;
};
int a[maxn][maxn];
bool b[maxn][maxn];
H team[maxn*4];
int s=0,t=0;
void bfs(int x,int y)
{
	team[t].x=x;
	team[t].y=y;
	t++;
	b[x][y]=true;
	while(s!=t)
	{
		H now=team[s];
		s++;
		for(int i=0;i<8;i++)
		{
			int xx=now.x+dx[i];
			int yy=now.y+dy[i];
			if(xx>=1&&xx<=n&&yy>=1&&yy<=m&&b[xx][yy]==false)
			{
				b[xx][yy]=true;
				a[xx][yy]=a[now.x][now.y]+1;
				team[t].x=xx;
				team[t].y=yy;
				t++;
			}
		}
	}
	for(int i=1;i<=n;i++)
	{
		for(int j=1;j<=m;j++)
		{
			if(b[i][j]==false)
			{
				a[i][j]=-1;
			}
		}
	}
	return ;
}
int main()
{
	scanf("%d%d%d%d",&n,&m,&x,&y);
	bfs(x,y);
	for(int i=1;i<=n;i++)
	{
		for(int j=1;j<=m;j++)
		{
			printf("%-5d",a[i][j]);
		}
		cout<<endl;
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/Rem_Inory/article/details/81591637