题目描述
有一个 n×m 的棋盘,在某个点 (x,y) 上有一个马,要求你计算出马到达棋盘上任意一个点最少要走几步。
输入格式
输入只有一行四个整数,分别为 n, m, x, y。
输出格式
一个 n×m 的矩阵,代表马到达某个点最少要走几步(左对齐,宽 5 格,不能到达则输出 −1)。
输入输出样例
输入 #1复制
3 3 1 1
输出 #1复制
0 3 2 3 -1 1 2 1 4
说明/提示
数据规模与约定
对于全部的测试点,保证 1≤x≤n≤400,1≤y≤m≤400。
解题思路:BFS + 模拟队列。
Code:
#include <iostream>
#include <stdio.h>
#include <cstring>
#include <iomanip>
using namespace std;
typedef pair<int, int> PII;
const int dx[8] = {-2, -1, 1, 2, 2, 1, -1, -2};
const int dy[8] = {1, 2, 2, 1, -1, -2, -2, -1};
const int N = 500;
int n, m, x, y;
int g[N][N], d[N][N];
PII q[N * N];
void bfs()
{
int hh = 0, tt = 0;
memset(d, -1, sizeof d);
d[x][y] = 0, q[0] = {x, y};
while(hh <= tt)
{
auto t = q[hh ++ ];
for(int i = 0; i < 8; i ++ )
{
int x1 = t.first + dx[i], y1 = t.second + dy[i];
if(x1 >= 1 && x1 <= n && y1 >= 1 && y1 <= m && d[x1][y1] == -1)
{
d[x1][y1] = d[t.first][t.second] + 1;
q[++ tt] = {x1, y1};
}
}
}
}
signed main()
{
scanf("%d%d%d%d", &n, &m, &x, &y);
bfs();
for(int i = 1; i <= n; i ++ )
{
for(int j = 1; j <= m; j ++ ) printf("%-5d",d[i][j]); //cout << left << setw(5) << setfill(' ') << d[i][j];
cout << endl;
}
}