洛谷P2298 Mzc和男家丁的游戏 题解

本题做法

  • BFS。

思路

简单的 BFS 打卡题。从 m 的位置开始 BFS,直到找到 d 的位置,此时由于是按照层序搜索的,所以步数一定是最少的,故直接输出步数,程序退出。最后如果 BFS 结束后依然没有输出,则直接输出 No Way!

代码

#include <bits/stdc++.h>
#define i64 long long
#define u64 unsigned long long
#define endl '\n'

using namespace std;

const int INF = 0x3f3f3f3f;
const double EPS = 1e-8;
const int N = 2005;
const int fx[5] = {0, 0, 1, 0, -1};
const int fy[5] = {0, 1, 0, -1, 0};

struct coord {
    int x;
    int y;
    int step;
};

int n, m, sx, sy, ex, ey, ans = INF;
char mp[N][N];
bool vis[N][N];

#define CHECK(x, y) \
    (x >= 1 && x <= n && y >= 1 && y <= m && mp[x][y] == '.' && !vis[x][y])

int main() {
    cin >> n >> m;
    for (int i = 1; i <= n; i++) {
        for (int j = 1; j <= m; j++) {
            cin >> mp[i][j];
            if (mp[i][j] == 'm') {
                sx = i;
                sy = j;
                mp[i][j] = '.';
            } else if (mp[i][j] == 'd') {
                ex = i;
                ey = j;
                mp[i][j] = '.';
            }
        }
    }
    coord cur = {sx, sy, 0};
    queue<coord> q;
    vis[sx][sy] = 1;
    q.push(cur);
    while (!q.empty()) {
        cur = q.front();
        q.pop();
        int x = cur.x, y = cur.y, s = cur.step;
        if (x == ex && y == ey) {
            cout << s << endl;
            return 0;
        }
        int tx, ty;
        for (int i = 1; i <= 4; i++) {
            tx = x + fx[i];
            ty = y + fy[i];
            if (CHECK(tx, ty)) {
                vis[tx][ty] = 1;
                q.push({tx, ty, s + 1});
            }
        }
    }
    cout << "No Way!" << endl;
    return 0;
}
posted @ 2025-03-24 19:47  2789617221guo  阅读(22)  评论(1)    收藏  举报