思路
这道题是一个典型的BFS题目
代码实现
因为马走日,每次有 个可能的方向
因此定义两个一维数组
int dx[] = {0, -2, -1, 1, 2, 2, 1, -1, -2};
int dy[] = {0, 1, 2, 2, 1, -1, -2, -2, -1};
//i为向第i个方向走的距离另外使用存储走到的每一个点,存储走到的每一个点的步数(因为起点不需要动,所以为,又因为无法走到的输出,所以全部初始化为)
struct Node{
int x, y;
};
queue<Node> qu;
memset(s, -1, sizeof(s));
int s[410][410];
s[x][y] = 0;
qu.push({x, y});
//x,y为题中所给数据将队列中的每一个点进行遍历,每次从队列取出一个位置 ,尝试 8 个方向,如果新位置 在棋盘内&未被访问过s[nx][ny] == -1,则,并加入队列。
while (!qu.empty()){
Node now = qu.front();
for(int i = 1; i <= 8; i++){
nx = now.x + dx[i];
ny = now.y + dy[i];
if (nx >= 1 && nx <= n && ny >= 1 && ny <= m && s[nx][ny] == -1){
qu.push({nx, ny});
s[nx][ny] = s[now.x][now.y] + 1;
}
}
}最后输出每一个点对应的步数
for (int i = 1; i <= n; i++){
for (int j = 1; j <= m; j++){
cout<< s[i][j] << " ";
}
cout<<'\n';
}代码
#include <bits/stdc++.h>
using namespace std;
int n, m, x, y;
int s[410][410];
int dx[9] = {0, -2, -1, 1, 2, 2, 1, -1, -2};
int dy[9] = {0, 1, 2, 2, 1, -1, -2, -2, -1};
struct Node
{
int a, b;
};
queue<Node> qu;
int main()
{
cin >> n >> m >> x >> y;
memset(s, -1, sizeof(s));
s[x][y] = 0;
qu.push({x, y});
while (!qu.empty())
{
Node now = qu.front();
int tx, ty;
qu.pop();
for (int i = 1; i <= 8; i++)
{
tx = now.a + dx[i];
ty = now.b + dy[i];
if (tx >= 1 && tx <= n && ty >= 1 && ty <= m && s[tx][ty] == -1)
{
qu.push({tx, ty});
s[tx][ty] = s[now.a][now.b] + 1;
}
}
}
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= m; j++)
{
cout << s[i][j] << " ";
}
cout << '\n';
}
return 0;
}