P2298 Mzc和男家丁的游戏

题目链接

https://www.luogu.com.cn/problem/P2298

题目思路

依旧是bfs,记得这个有 无答案 情况

题目代码

#include <iostream>
#include <algorithm>
#include <cstring>
#include <queue>

using namespace std;
typedef pair<int, int> PII;
const int N = 2010;
char g[N][N];
int dist[N][N];
bool st[N][N];
int n, m;

int bfs(int x, int y)
{
    memset(dist, -1, sizeof dist);
    queue<PII> q;
    q.push({x, y});
    dist[x][y] = 0;
    st[x][y] = true;
    while(q.size())
    {
        auto t = q.front();
        q.pop();
        int dx[4] = {-1, 0, 1, 0}, dy[4] = {0, 1, 0, -1};
        for(int i = 0; i < 4; i ++ )
        {
            int a = t.first + dx[i], b = t.second + dy[i];
            if(a >= 0 && a < n && b >= 0 && b < m && g[a][b] != '#' && !st[a][b])
            {
                dist[a][b] = dist[t.first][t.second] + 1;
                st[a][b] = true;
                if(g[a][b] == 'd')
                {
                    return dist[a][b];
                }
                q.push({a, b});
            }
        }
    }
    return -1;
}

int main()
{
    memset(g, '#', sizeof g);
    cin >> n >> m;
    for(int i = 0; i < n; i ++ ) cin >> g[i];
    int x, y;
    for(int i = 0; i < n; i ++ )
    {
        for(int j = 0; j < m; j ++ )
            if(g[i][j] == 'm')
                x = i, y = j;
    }
    int t = bfs(x, y);
    if(t == -1) cout << "No Way!" << endl;
    else cout << t << endl;
    return 0;
}
posted @   vacilie  阅读(16)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
· .NET周刊【3月第1期 2025-03-02】
点击右上角即可分享
微信分享提示
主题色彩