题目大意:地图中的五种元素:0代表墙 1代表空地 2代表人的起点 3代表出口 4代表炸弹的重启器 炸弹只有6秒的时间,地图中的任何地方都可以走多遍,如果遇到4,那么炸弹的时间被重置为6,要求算出人到达出口的最短时间。
解题思路: BFS,走过的路不用标记,大于1时间的才可以入队,遇到4置时间为6即可
代码:
#include <iostream>
#include <cstdio>
#include <queue>
using namespace std;
const int N = 10;
int map[N][N], n, m, starti, startj;
int dir[][2] = {{-1,0}, {0,1}, {1,0}, {0,-1}};
struct Node
{
int x, y, curtime, bombtime;
};
int dfs()
{
queue<Node> q;
Node now, next;
now.x = starti, now.y = startj, now.curtime = 0, now.bombtime = 6;
q.push(now);
map[now.x][now.y] = 0;
while (!q.empty())
{
now = q.front();
q.pop();
for (int i = 0; i < 4; ++i)
{
next.x = now.x + dir[i][0];
next.y = now.y + dir[i][1];
if (next.x>=0 && next.x<n && next.y>=0 && next.y<m &&
map[next.x][next.y] != 0 && now.bombtime > 1)
{
if (map[next.x][next.y] == 3)
return now.curtime + 1;
else if (map[next.x][next.y] == 1)
{
next.curtime = now.curtime + 1;
next.bombtime = now.bombtime - 1;
q.push(next);
}
else if (map[next.x][next.y] == 4)
{
next.curtime = now.curtime + 1;
next.bombtime = 6;
q.push(next);
map[next.x][next.y] = 0;
}
}
}
}
return -1;
}
int main()
{
int t;
scanf("%d", &t);
while (t--)
{
scanf("%d %d", &n, &m);
for (int i = 0; i < n; ++i)
for (int j = 0; j < m; ++j)
{
scanf("%d", &map[i][j]);
if (map[i][j] == 2)
starti = i, startj = j;
}
printf("%d\n", dfs());
}
return 0;
}