hdoj1072 Nightmare bfs

时间:2024-07-18 11:06:08

题意:在一个地图里逃亡,2是起点,3是终点,1是路,0是墙,逃亡者携带一个炸弹,6分钟就会炸,要在6分钟前到达4可以重制时间,问是否能逃亡,若能则输出最小值

我的思路:bfs在5步内是否存在3,存在则输出退出。记录到达每一点剩余时间,如果再次到达某点的剩余时间大于原剩余时间则更新,加入队列。

 #include <iostream>
#include <cstring>
#include <queue> using namespace std;
const int M = ;
int map[M][M];
int graph[M][M];
struct node
{
int x,y;
int step;
int time;
}; node now,nn,next1;
queue <struct node> q;
int n,m;
int dire[][] = {{-,},{,-},{,},{,}}; int bfs()
{
while (!q.empty())
{
now = q.front();
q.pop();
for (int i = ;i < ;i++)
{
int x = now.x + dire[i][];
int y = now.y + dire[i][];
if (x>= && x<n && y>= && y<m && map[x][y] != && map[x][y]!= && now.time->) //踩点到到达4也会爆炸
{
next1.x = x;
next1.y = y;
if (map[x][y] == )
{
return now.step+;
}
if (map[x][y] == )
{
next1.time = ;
}
else next1.time = now.time - ;
next1.step = now.step+;
if (next1.time > graph[x][y]) //加入队列条件
{
graph[x][y] = next1.time;
q.push(next1);
}
}
}
}
return -;
}
int main()
{
int t;
cin >> t;
while (t--)
{
cin >> n >> m;
while (!q.empty())
q.pop();
for (int i = ;i < n;i++)
{
for (int j = ;j < m;j++)
{
cin >> map[i][j];
graph[i][j] = ;
if (map[i][j] == )
{
nn.x = i;
nn.y = j;
nn.step = ;
nn.time = ;
q.push(nn);
}
}
}
cout << bfs() << endl;
}
return ;
}