蓝桥杯备考:BFS之马的遍历
这道题我们得知道象棋里的马能怎么走,应该是按日字走的
如图,就这么走,我们按基础的bfs遍历一下标记每个格子的最短的路径就行了,没到达的格子就设置为-1
#include <iostream>
#include <queue>
#include <cstring>
using namespace std;
const int N = 410;
int n, m, x, y;
int dict[N][N];
int dx[] = { -2,-1,1,2,2,1,-1,-2 };
int dy[] = { 1,2,2,1,-1,-2,-2,-1 };
typedef pair<int, int> PII;
void bfs() {
memset(dict, -1, sizeof(dict));
queue<PII> q;
q.push({ x,y });
dict[x][y] = 0;
while (q.size())
{
auto t = q.front();
q.pop();
int x = t.first;
int y = t.second;
for (int k = 0; k < 8; k++)
{
int px = x + dx[k];
int py = y + dy[k];
if (px<1 || py<1 || px>n || py>m)continue;
if (dict[px][py] != -1) continue;
dict[px][py] = dict[x][y] + 1;
q.push({ px,py });
}
}
}
int main()
{
cin >> n >> m >> x >> y;
bfs();
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= m; j++)
{
cout << dict[i][j] << " ";
}
cout << endl;
}
return 0;
}