[AcWing 188] 武士风度的牛
作者:互联网
BFS 记录距离
点击查看代码
#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
const int N = 1000 + 10;
#define x first
#define y second
int n, m;
char g[N][N];
int dx[] = {-2, -2, -1, -1, 1, 1, 2, 2};
int dy[] = {-1, 1, -2, 2, -2, 2, -1, 1};
int d[N][N];
int bfs(int x, int y)
{
queue<pair<int,int>> q;
q.push({x, y});
memset(d, -1, sizeof d);
d[x][y] = 0;
while (q.size()) {
auto t = q.front();
q.pop();
for (int i = 0; i < 8; i ++) {
int a = t.x + dx[i], b = t.y + dy[i];
if (a < 1 || a > n || b < 1 || b > m || g[a][b] == '*' || d[a][b] != -1)
continue;
if (g[a][b] == 'H')
return d[t.x][t.y] + 1;
q.push({a, b});
d[a][b] = d[t.x][t.y] + 1;
}
}
}
void solve()
{
cin >> m >> n;
int sx = 0, sy = 0;
for (int i = 1; i <= n; i ++)
for (int j = 1; j <= m; j ++) {
cin >> g[i][j];
if (g[i][j] == 'K')
sx = i, sy = j;
}
cout << bfs(sx, sy) << endl;
}
signed main()
{
ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
solve();
return 0;
}
- \(BFS\) 的同时记录到起点的距离(即跳了多少次),\(dx\) 和 \(dy\) 是“日”字的形式
标签:int,风度,BFS,long,dx,dy,188,define,AcWing 来源: https://www.cnblogs.com/wKingYu/p/16544827.html