https://www.luogu.org/problemnew/show/P1443
题目描述
有一个n*m的棋盘(1<n,m<=400),在某个点上有一个马,要求你计算出马到达棋盘上任意一个点最少要走几步
输入输出格式
输入格式:
一行四个数据,棋盘的大小和马的坐标
输出格式:
一个n*m的矩阵,代表马到达某个点最少要走几步(左对齐,宽5格,不能到达则输出-1)
输入输出样例
输入样例#1:
3 3 1 1
输出样例#1:
0 3 2
3 -1 1
2 1 4
//裸的bfs,就当随便记录一下吧~
ac_code:
#include <bits/stdc++.h>
using namespace std;
struct point
{
int x,y;
int cnt;
point(int xx,int yy,int ct = 0):x(xx),y(yy),cnt(ct){}
};
int step[8][2]=
{
-2,-1,-1,-2,-2,1,-1,2,
1,-2,2,-1,1,2,2,1
};
int n,m,sx,sy;
bool vis[405][405];
int mp[405][405];
void bfs()
{
point s(sx,sy);
queue<point>q;
q.push(s);
vis[s.x][s.y] = true;
while(!q.empty())
{
point k = q.front();
q.pop();
for(int i = 0; i < 8; i++)
{
int xx = k.x + step[i][0];
int yy = k.y + step[i][1];
if(xx<1||xx>n||yy<1||yy>m||vis[xx][yy])
continue;
vis[xx][yy] = true;
mp[xx][yy] = k.cnt+1;
q.push(point(xx,yy,k.cnt+1));
}
}
}
int main()
{
cin>>n>>m>>sx>>sy;
bfs();
cout.setf(ios::left);
for(int i = 1; i <= n; i++)
{
for(int j = 1; j <= m; j++)
{
cout.width(5);
if(i == sx && j == sy)
{
cout<<0;
}
else
{
cout<<(mp[i][j] ? mp[i][j] : -1);
}
}
cout<<endl;
}
return 0;
}