题目:P1143 代码:
#include <bits/stdc++.h>
using namespace std;
int n, m;
int dx[8] = {2, 2, -2, -2, 1, 1, -1, -1}; // 正确的dx数组
int dy[8] = {1, -1, 1, -1, 2, -2, 2, -2}; // 正确的dy数组
int a[405][405];
queue<pair<int, int>> q;
void bfs(int x, int y)
{
q.push(make_pair(x, y));
while (!q.empty())
{
int xx = q.front().first, yy = q.front().second;
q.pop();
for (int i = 0; i < 8; i++)
{
int nx = xx + dx[i], ny = yy + dy[i];
if (nx >= 1 && nx <= n && ny >= 1 && ny <= m && a[nx][ny] == -1)
{
a[nx][ny] = a[xx][yy] + 1; // 更新步数
q.push(make_pair(nx, ny)); // 将新位置加入队列
}
}
}
}
int main()
{
int x, y;
cin >> n >> m >> x >> y; // 输入棋盘大小和起点位置
for (int i = 1; i <= n; i++)
for (int j = 1; j <= m; j++)
a[i][j] = -1; // 初始化棋盘,所有位置标记为-1(未访问)
a[x][y] = 0; // 起点位置步数为0
bfs(x, y); // 从起点开始BFS
for (int i = 1; i <= n; i++) // 输出结果
{
for (int j = 1; j <= m; j++)
{
cout << a[i][j] << " ";
}
cout << endl;
}
return 0;
}