题意:
你手上有一个炸弹,6分钟后会爆炸,现在给你一张图,你走到出口时炸弹没有爆炸你就安全了。
图上有很多重设时间点,走到重设时间点可以把时间重新设置为6分钟,你可以走上下左右四个方向,每走一步消耗一分钟。
现在要输出最短逃出时间,若逃不出输出-1。
图上0:代表墙, 1:代表可以走的路, 2:代表你的位置, 3:代表出口的位置,4:代表炸弹重设时间点。
解析:
用bfs来找逃出最短时间。
与普通的bfs不同的地方在于入队条件。
如下图:
2 1 0 1
1 1 0 3
0 1 0 1
4 1. 1 1
从2点出发想要到达3点,必须经过4点去重设时间6。
当到达图中1.点时,行走路径是 1. -> 4 -> 1.
因此,新建一个时间戳来记录当前点的炸弹时间,入队的条件修改为原来的爆炸时间戳小于当前的爆炸时间。
看代码好理解。
代码:
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <cstring>
#include <cmath>
#include <stack>
#include <vector>
#include <queue>
#include <map>
#define LL long long
#define lson lo, mi, rt << 1
#define rson mi + 1, hi, rt << 1 | 1
using namespace std;
const int maxn = 10;
const int inf = 0x3f3f3f3f;
const double eps = 1e-8;
const double pi = acos(-1.0);
const double ee = exp(1.0);
int dir[][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
int n, m;
int g[maxn][maxn];
int timeMark[maxn][maxn];
struct Point
{
int x, y, step, time;
Point(int _x, int _y, int _step, int _time)
{
x = _x;
y = _y;
step = _step;
time = _time;
}
};
int bfs(int sx, int sy, int ex, int ey)
{
queue<Point> q;
q.push(Point(sx, sy, 0, 6));
timeMark[sx][sy] = 6;
while (!q.empty())
{
Point now = q.front();
q.pop();
int x = now.x;
int y = now.y;
int step = now.step;
int time = now.time;
if (x == ex && y == ey)
{
return step;
}
if (g[x][y] == 4)
{
time = 6;
timeMark[x][y] = 6;
}
for (int i = 0; i < 4; i++)
{
int nx = x + dir[i][0];
int ny = y + dir[i][1];
int nstep = step + 1;
int ntime = time - 1;
if (0 <= nx && nx < n && 0 <= ny && ny < m && g[nx][ny] != 0 && 0 < ntime)
{
if (timeMark[nx][ny] < ntime)
{
timeMark[nx][ny] = ntime;
q.push(Point(nx, ny, nstep, ntime));
}
}
}
}
return -1;
}
int main()
{
#ifdef LOCAL
freopen("in.txt", "r", stdin);
#endif // LOCAL
int ncase;
scanf("%d", &ncase);
while (ncase--)
{
scanf("%d%d", &n, &m);
int sx, sy;
int ex, ey;
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
scanf("%d", &g[i][j]);
if (g[i][j] == 2)
{
sx = i;
sy = j;
}
if (g[i][j] == 3)
{
ex = i;
ey = j;
}
}
}
memset(timeMark, 0, sizeof(timeMark));
int ans = bfs(sx, sy, ex, ey);
printf("%d\n", ans);
}
return 0;
}