题目简介
一天,sunny 不小心进入了一个迷宫,不仅很难寻找出路,而且有的地方还有怪物,但是 sunny 有足够的能力杀死怪物,但是需要一定的时间,但是 sunny 想早一点走出迷宫,所以请你帮助他计算出最少的时间走出迷宫,输出这个最少时间。
我们规定每走一格需要时间单位 1, 杀死怪物也需要时间 1, 如果不能走到出口,则输出 impossible. 每次走只能是上下左右 4 个方向。
说明
先四面造墙,省去判断是否出界的函数。之后对于有怪物的格子,新状态再搜索树中是当前状态的下两层的,因此不能走过之后直接step+2标记掉,而是要记录下这个状态(cnt=1)。很容易WA的点。
#include <cstdio>
#include <queue>
using namespace std;
#define NEXT mp[p.x+dx[i]][p.y+dy[i]]
struct node{int x, y, step, cnt;};
char mp[202][202];
int sx, sy, n, m, i;
const int dx[4] = {-1, 0, 1, 0};
const int dy[4] = {0, 1, 0, -1};
void bfs()
{
queue<node> q;
q.push({sx, sy, 0, 0});
mp[sx][sy] = '#';
while (!q.empty()){
node p = q.front();
q.pop();
if (p.cnt == 1){
p.cnt = 0;
q.push(p);
continue;
}
for (i = 0; i < 4; ++i)
switch(NEXT){
case '.': NEXT = '#'; q.push({p.x+dx[i], p.y+dy[i], p.step+1, 0}); break;
case 'X': NEXT = '#'; q.push({p.x+dx[i], p.y+dy[i], p.step+2, 1}); break;
case 'T': printf("%d\n", p.step+1); return;
}
}
printf("impossible\n");
}
void init()
{
sx = sy = 0;
for (i = 1; i <= n; ++i){
for (int j = 1; j <= m; ++j){
scanf("%c", &mp[i][j]);
if (mp[i][j] == 'S') sx = i, sy = j;
}
getchar();
}
for (i = 0; i <= m+1; ++i)
mp[0][i] = mp[n+1][i] = '#';
for (i = 0; i <= n+1; ++i)
mp[i][0] = mp[i][m+1] = '#';
}
int main()
{
while (~scanf("%d%d\n", &n, &m)){
init();
bfs();
}
return 0;
}