蓝桥杯随笔练——迷宫和陷阱

题目:迷宫和陷阱BFS

来源:2018年国赛C/C++C组第6题

声明:我只拿30%的分,我也不知道为什么不对呜呜呜呜

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

using namespace std;

const int N = 1e3 + 10;
int n, k;
char g[N][N];       // 存储迷宫
int vis[N][N];      // 标记是否访问过
int last[N][N];     // 记录每个位置的无敌状态剩余步数
int dx[] = {0, -1, 0, 1};
int dy[] = {-1, 0, 1, 0};

struct node {
    int x, y;       // 坐标
    int step;       // 走到该坐标的步数
    int status;     // 无敌状态剩余步数
};

int bfs(int x1, int y1) {
    memset(vis, 0, sizeof(vis));      // 初始化 vis 数组
    memset(last, -1, sizeof(last));   // 初始化 last 数组
    queue<node> q;
    q.push({x1, y1, 0, 0});          // 起点
    vis[x1][y1] = 1;                 // 标记起点为已访问

    while (!q.empty()) {
        auto t = q.front();
        q.pop();

        for (int i = 0; i < 4; i++) {
            int a = t.x + dx[i];
            int b = t.y + dy[i];
            int c = t.step + 1;      // 步数加 1
            int d = t.status > 0 ? t.status - 1 : 0; // 更新无敌状态

            if (a == n && b == n) return c; // 到达终点

            if (a < 1 || a > n || b < 1 || b > n || g[a][b] == '#') continue; // 越界或撞墙
            if (g[a][b] == 'X' && d == 0) continue; // 是陷阱且没有无敌状态

            if (g[a][b] == '%') {
                q.push({a, b, c, k}); // 拾取解药,重置无敌状态
                last[a][b] = k;
                vis[a][b] = 1;
                g[a][b] = '.';       // 解药被拾取后变为空地
            } else {
                if (!vis[a][b] || d > last[a][b]) { // 未访问过或新的无敌状态更优
                    vis[a][b] = 1;
                    last[a][b] = d;
                    q.push({a, b, c, d});
                }
            }
        }
    }
    return -1; // 无法到达终点
}

int main() {
    cin >> n >> k;
    for (int i = 1; i <= n; i++) {
        for (int j = 1; j <= n; j++) {
            cin >> g[i][j];
        }
    }

    cout << bfs(1, 1) << endl;
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值