题目大意:在迷宫中有一个炸弹,过六个单位时间就会爆炸,要你求一个起点到迷宫的终点的最短距离,迷宫中有时间重置器,当你走到这个格子,炸弹的爆炸时间重新置为0,迷宫中标识为墙壁的格子不能走,到达任意一个格子时,炸弹计数器为0时,则失败
解题思路:最短距离,就想到用宽度优先遍历,但是要一个辅助的数组来保存每个格子的时间信息。
之前受hdoj 1242的影响,认为格子保存的是当前走过路程的最小值,w了很多次。。。。以为每个格子前进一步的花费时间单位是一样的,所以宽度遍历的结果自然是最短距离,由于时间单位有限制,只能走六个单元,只有在这六个时间单位里到达了终点,或者走到了时间设置开关把炸弹计时器置为0才能继续走下去,所以要一个辅助数组来保存每个格子剩余的最大时间单位,只有走到当前的格子的剩余时间单位比之前的大时,这个状态才能加入队列中
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <queue>
#include <algorithm>
using namespace std;
struct node
{
int x, y;
int step;
int t;
};
const int maxn = 9;
int dir[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
int maze[maxn][maxn], graph[maxn][maxn];
int n, m, ex, ey, ans;
bool bfs(int x, int y);
int main()
{
int test;
scanf("%d", &test);
while(test-- != 0)
{
scanf("%d %d", &n, &m);
int sx, sy;
for(int i = 0; i < n; i++)
{
for(int j = 0; j < m; j++)
{
scanf("%d", &maze[i][j]);
if(maze[i][j] == 2)
sx = i, sy = j;
if(maze[i][j] == 3)
ex = i, ey = j;
graph[i][j] = 0;
}
}
if(bfs(sx, sy))
printf("%d\n", ans);
else
printf("-1\n");
}
return 0;
}
bool bfs(int x, int y)
{
queue<node> que;
node s;
s.x = x;
s.y = y;
s.step = 0;
s.t = 6;
graph[x][y] = 6;
que.push(s);
while(!que.empty())
{
node st = que.front();
que.pop();
if(st.x == ex && st.y == ey)
{
ans = st.step;
return true;
}
if(st.t == 1)
continue;
for(int i = 0; i < 4; i++)
{
int dx = st.x + dir[i][0];
int dy = st.y + dir[i][1];
if(dx >= 0 && dx < n && dy >= 0 && dy < m && maze[dx][dy] != 0)
{
node tmp;
tmp.x = dx; tmp.y = dy;
tmp.step = st.step + 1;
tmp.t = st.t - 1;
if(maze[dx][dy] == 4)
tmp.t = 6;
if(tmp.t > graph[dx][dy])
{
graph[dx][dy] = tmp.t;
que.push(tmp);
}
}
}
}
return false;
}