洛谷P1443 传送门
这题比较水,主要是要学一下优先队列和结构体一起使用的方法还有重载结构体的优先级
水题,初始化地图为-1
,然后八个方向的bfs搜索即可
代码如下:
#include <stdio.h>
#include <cstring>
#include <iostream>
#include <string>
#include <cmath>
#include <algorithm>
#include <cstdlib>
#include <queue>
#include <deque>
#include <cstring>
#include <iterator>
#include <set>
#include <map>
#define ll long long
using namespace std;
int mp[405][405];
int vis[405][405];
int mov[8][2] = {-2, -1, 2, 1, 2, -1, -2, 1, 1, 2, -1, -2, 1, -2, -1, 2};
int n, m, sx, sy;
struct horse
{
int x, y, step;
} a, b;
queue<horse> q;
void bfs()
{
while (!q.empty())
{
a = q.front();
q.pop();
mp[a.x][a.y] = a.step;
for (int i = 0; i < 8; i++)
{
int xx = a.x + mov[i][0];
int yy = a.y + mov[i][1];
if (xx < 1 || yy < 1 || xx > n || yy > m || vis[xx][yy])
continue;
vis[xx][yy] = 1;
b.x = xx;
b.y = yy;
b.step = a.step + 1;
q.push(b);
}
}
}
int main()
{
cin >> n >> m >> sx >> sy;
memset(mp, -1, sizeof(mp));
a.x = sx;
a.y = sy;
a.step = 0;
q.push(a);
vis[sx][sy] = 1;
bfs();
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= m; j++)
printf("%-5d", mp[i][j]);
cout << endl;
}
return 0;
}