今天继续巩固一下bfs的知识,练习了一道bfs的题目。队列与bfs算法结合更加方便代码的编写。
# 马的遍历
## 题目描述
有一个 $n \times m$ 的棋盘,在某个点 $(x, y)$ 上有一个马,要求你计算出马到达棋盘上任意一个点最少要走几步。
## 输入格式
输入只有一行四个整数,分别为 $n, m, x, y$。
## 输出格式
一个 $n \times m$ 的矩阵,代表马到达某个点最少要走几步(不能到达则输出 $-1$)。
## 样例 #1
### 样例输入 #1
```
3 3 1 1
```
### 样例输出 #1
```
0 3 2
3 -1 1
2 1 4
```
---------------------------------------------------------------------------------------------
#include<iostream>
#include<cstring>
#include<queue>
using namespace std;
int ans[400][400];
bool add[400][400];
int n, m, x, y;
int dx[8] = {2,1,-1,-2,-2,-1,1,2};
int dy[8] = {1,2,2,1,-1,-2,-2,-1};
queue<pair<int, int>>s;
void bfs(int a, int b) {
s.push(make_pair(a,b));
ans[s.front().first][s.front().second] = 0;
add[a][b] = true;
while (!s.empty()) {
int x1 = s.front().first;
int y1 = s.front().second;
s.pop();
for(int i = 0; i < 8; i++) {
int x2 = x1 + dx[i];
int y2 = y1 + dy[i];
if (x2 >= 1 && x2 <= n && y2 <= m && y2 >= 1 && !add[x2][y2]) {
ans[x2][y2] = ans[x1][y1] + 1;
s.push(make_pair(x2, y2));
add[x2][y2] = true;
}
}
}
}
int main()
{
cin >> n >> m >> x >> y;
memset(ans, -1, sizeof(ans));
bfs(x, y);
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
cout << ans[i][j] << " ";
}
cout << endl;
}
return 0;
}