题目链接http://acm.hdu.edu.cn/showproblem.php?pid=1072
一个人梦见自己背着炸弹走迷宫,炸弹会在6min后爆炸。若能从起点走到终点输出最短时间,否则输出-1。
矩阵数字0:不可走 1:可走2:起点3:终点4:炸弹时间重置为6
广搜就可以,用一个结构体成员time记录剩余爆炸时间,step记录步数。
#include <iostream>
#include <cstdio>
#include <queue>
using namespace std;
int dir[][2] = {0,-1, -1,0, 0,1, 1,0};
int n, m, map[10][10], startx, starty;
struct Node
{
int x, y, time, step;
};
int bfs()
{
Node now, next;
now.x = startx, now.y = starty, now.time = 6, now.step = 0;
map[now.x][now.y] = 0;
queue<Node> q;
q.push(now);
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];
next.time = now.time - 1, next.step = now.step + 1;
if (next.x>=0 && next.x<n && next.y>=0 && next.y<m &&
map[next.x][next.y] != 0 && next.time > 0)
{
if (map[next.x][next.y] == 3)
return next.step;
else if (map[next.x][next.y] == 4)
{
next.time = 6;
map[next.x][next.y] = 0;
}
q.push(next);
}
}
}
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)
{
startx = i;
starty = j;
}
}
printf("%d\n", bfs());
}
return 0;
}