[AcWing 188] 武士风度的牛

image
image
image

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;
}

  1. \(BFS\) 的同时记录到起点的距离(即跳了多少次),\(dx\)\(dy\) 是“日”字的形式
posted @ 2022-08-02 18:38  wKingYu  阅读(22)  评论(0编辑  收藏  举报