https://www.luogu.org/problem/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
代码
/*
注意:
是n行m列
*/
#include<algorithm>
#include<string.h>
#include<iostream>
#include<stdio.h>
#include<queue>
using namespace std;
const int maxn = 410;
int d[2][8] = { {1, 1,2, 2,-1,-1,-2,-2},
{ 2,-2,1,-1, 2,-2, 1,-1} };
int n, m;
int x, y;
int g[maxn][maxn];
int visited[maxn][maxn];
struct node
{
int a, b;
node(int x, int y) :a(x), b(y) {}
};
int borderline(int x, int y)
{
return (x > 0 && x <= n && y > 0 && y <= m);
}
void bfs()
{
queue <node> q;
q.push(node(x, y));
while (!q.empty())
{
node t = q.front(); q.pop();
for (int i = 0; i < 8; i++)
{
int tx = t.a + d[0][i];
int ty = t.b + d[1][i];
if (borderline(tx, ty) && !visited[tx][ty])
{
visited[tx][ty] = 1;
g[tx][ty] = g[t.a][t.b] + 1;
q.push(node(tx, ty));
}
}
}
}
int main()
{
scanf("%d%d%d%d", &n, &m, &x, &y);
memset(g, -1, sizeof g);
g[x][y] = 0;
bfs();
g[x][y] = 0;
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= m; j++)
printf("%-5d", g[i][j]);
puts("");
}
return 0;
}