解题过程:刚看到这道题的样例本蒟蒻不能理解输出怎么来的,开始我以为小马是一格格走的不过模拟了一下样例发现不符合结果,看题目也没有发现怎么走的,于是想到了象棋中马走‘日’字然后模拟下样例发现与输出一致。
然后是小马可能到达的位置:绿色点假设表示小马初始位置,则八个黑色的点表示小马可以到达的位置。
可以用偏移量来表示小马到达的位置 :int dx[9] = {-1,-2,-2,-1,1,2,2,1};
int dy[9] ={-2,-1,1,2,2,1,-1,-2};
则位置表示为(x + dx[i],y + dy[i]);
具体解题过程:使用 BFS 遍历 n*m 棋盘的所有点,记录每个点到起点的距离即可。
#include<bits/stdc++.h>//万能头文件
using namespace std;
typedef long long ll;
const int N = 450;//宏定义
int dx[9] = {-1,-2,-2,-1,1,2,2,1};//小马横坐标偏移量
int dy[9] = {-2,-1,1,2,2,1,-1,-2};//小马纵坐标偏移量
int n,m,x,y;//题目要求输入的数据
int h[N][N];//表示
bool vis[N][N];//表示该点马是不是到达过
int main()
{
ios::sync_with_stdio(0);
cin.tie(0), cout.tie(0);
cin >> n >> m >> x >> y;//输入数据
memset(h,-1,sizeof(h));//初始化为-1
queue<pair<int,int>>q;
q.push({x,y}),vis[x][y] = true,h[x][y] = 0;//初始化
while(!q.empty())//bfs
{
int xx = q.front().first;
int yy = q.front().second;
q.pop();//取队首并出队
for(int i=0; i<8; i++)
{
int fx = xx + dx[i];
int fy = yy + dy[i];
if(fx < 1 || fx > n || fy < 1 || fy > m || vis[fx][fy]) continue;//出界或走过就不走
vis[fx][fy] = true;
q.push({fx,fy});
h[fx][fy] = h[xx][yy] + 1;
}
}
for(int i=1; i<=n; i++)
{
for(int j=1; j<=m; j++)
{
if(!vis[i][j]) cout<<setw(5)<<-1<<' ';
else cout<<setw(5)<<h[i][j]<<' ';//注意间距为5
}
cout<<'\n';
}
return 0;
}