(兴趣是最好的老师!!!)
//广度优先搜索入门(bfs)
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<queue>
using namespace std;
struct xy {
int x, y;
}node, Top;
const int dx[4] = { 1,-1,2,-2 };
const int dy[4] = { 1,-1,2,-2 };
int a[401][401];//到(x,y)处的步数
bool b[401][401];
int n, m;
void bfs(int x, int y, int step) {
a[x][y] = step;
b[x][y] = false;//将开始的节点设置为已经访问
queue<xy> Q;//创建一个基于结构 xy 的队列Q
node.x = x;
node.y = y;
Q.push(node);//node 入队
while (!Q.empty()) {
Top = Q.front();//记录队列首个元素(先进先出)
Q.pop();//弹出队列(先进先出)
for (int i = 0;i < 4;i++) {
for (int j = 0;j < 4;j++) {
if (abs(dx[i]) != abs(dy[j])) {//马走日的条件
int NewX = Top.x + dx[i];
int NewY = Top.y + dy[j];//来到新位置
if (NewX<1 || NewY<1 || NewY>m || NewX>n) continue;//新的位置不可以出界
if (b[NewX][NewY]) {//如果新位置未被访问过
node.x = NewX;
node.y = NewY;
Q.push(node);//逐层压入需要判断的坐标(bfs思想)
b[NewX][NewY] = false;//记录被访问过了
a[NewX][NewY] = a[Top.x][Top.y] + 1;//步数加一
}
}
}
}
}
}
int main() {
memset(b, true, sizeof(b));
memset(a, -1, sizeof(a));
int x, y;
cin >> n >> m >> x >> y;
bfs(x, y, 0);
for (int i = 1;i <= n;i++) {
for (int j = 1;j <= m;j++) {
printf("%-5d", a[i][j]);//左对齐五格输出
}
cout << endl;
}
return 0;
}