题目描述
有一个n*m的棋盘(1<n,m<=400),在某个点上有一个马,要求你计算出马到达棋盘上任意一个点最少要走几步
输入格式
一行四个数据,棋盘的大小和马的坐标
输出格式
一个n*m的矩阵,代表马到达某个点最少要走几步(左对齐,宽5格,不能到达则输出-1)
输入输出样例
输入
3 3 1 1
输出
0 3 2
3 -1 1
2 1 4
题解
#include<iostream>
#include<iomanip>
#include<queue>
using namespace std;
struct chb {
int x; int y;
};
/
int c[8][2] = { -2,-1,-2,1,2,-1,2,1,-1,-2,1,-2,-1,2,1,2 };
int che[402][402];
int m, n;
//创建广搜队列
queue<chb>h;
//bool类型函数,判断当前到达该点是否还没存入最小步数以及该点是否在棋盘内,是返回ture,否返回false
bool r(int x, int y)
{
if (x < 0 || x >= m || y < 0 || y >= n || che[x][y] != -1)
return false;
return true;
}
void bfs(int x,int y)
{
//入队新节点
chb ne;
ne.x = x; ne.y = y; che[x][y] = 0;
h.push(ne);
//bfs搜索
while (!h.empty())
{
//八个方向入队
for (int i = 0; i < 8; i++)
{
ne.x = h.front().x + c[i][0];
ne.y = h.front().y + c[i][1];
if (r(ne.x, ne.y))
{
h.push(ne);
//步数加一
che[ne.x][ne.y] = che[h.front().x][h.front().y] + 1;
}
}
//对头出队
h.pop();
}
}
int main()
{
int x, y;
cin >> m >> n >> x >> y;
for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++)
che[i][j] = -1;
bfs(x - 1, y - 1);
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
//格式化输出
cout << setw(4)<<left<<che[i][j] << " ";
cout << endl;
}
return 0;
}