题目描述
有一个n*m的棋盘(1<n,m<=400),在某个点上有一个马,要求你计算出马到达棋盘上任意一个点最少要走几步
输入
一行四个数据,棋盘的大小和马的坐标
输出
一个n*m的矩阵,同一行元素之间用空格分离。代表马到达某个点最少要走几步。不能到达则输出-1。
样例输入
3 3 1 1
样例输出
0 3 2
3 -1 1
2 1 4
AC代码
//
// main.cpp
// 马的遍历
//
// Created by HISS on 2020/10/31.
// Copyright © 2020 HISS. All rights reserved.
//
#include <iostream>
#include <queue>
using namespace std;
//记录步数
struct node
{
int x;
int y;
int step;
};
int n, m, x, y;
int map[410][410];
//8个方向
int X[8] = {1, -1, 2, -2, 2, -2, 1, -1};
int Y[8] = {2, 2, 1, 1, -1, -1, -2, -2};
//判断是否可走
bool judge(int p, int q)
{
if(p < 1 || p > n || q < 1 || q > m)
return false;
//走过
else if(map[p][q] != -1)
return false;
else
return true;
}
void BFS()
{
queue<node> q;
node t1 = {x, y, 0};
q.push(t1);
//不要忘了这个
map[x][y] = 0;
while(!q.empty())
{
t1 = q.front();
q.pop();
for(int i = 0; i < 8; i ++)
{
if (judge(t1.x + X[i], t1.y + Y[i]))
{
node t2 = {t1.x + X[i], t1.y + Y[i], t1.step + 1};
q.push(t2);
map[t2.x][t2.y] = t2.step;
}
}
}
}
int main()
{
for (int i = 0; i < 410; i++)
for (int j = 0; j < 410; j++)
map[i][j] = -1;
cin >> n >> m >> x >> y;
BFS();
for (int i = 1; i <=n; i++)
{
for (int j = 1; j <= m; j++) //注意输出格式
cout << map[i][j] << " " ; //左对齐,宽5格
cout << endl;
}
return 0;
}