题目:迷宫和陷阱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;
}