hdoj1072 Nightmare(bfs)

时间:2023-03-09 08:57:54
hdoj1072 Nightmare(bfs)

题目大意:

在迷宫中有一个炸弹,过六个单位时间就会爆炸,要你求一个起点到迷宫的终点的最短距离,迷宫中有时间重置器,当你走到这个格子,炸弹的爆炸时间重新置为0,迷宫中标识为墙壁的格子不能走,到达任意一个格子时,炸弹计数器为0时,则失败。

求逃出迷宫最短距离,bfs。

但是有两个限制条件,1.求最短,2.炸弹时间不小于1(等于零不OK)。

解锁bfs新姿势。(赞!

 #include<iostream>
#include<cstring>
#include<queue>
#define maxn 10
using namespace std;
const int dx[]={-,,,},dy[]={,,-,};
int map[maxn][maxn],V[maxn][maxn];
struct point{
int x,y;
int temp,time; // 步数,剩余时间
}start;
int ans,n,m;
int bfs(){
queue<point> Q;
Q.push(start);
while (!Q.empty()){
point pre=Q.front();
if (map[pre.x][pre.y]== && pre.time>){
ans=pre.temp;
return ;
}
Q.pop();
for (int i=;i<;i++){
point next;
next.x=pre.x+dx[i];
next.y=pre.y+dy[i];
next.temp=pre.temp+;
next.time=pre.time-;
if (next.x< || next.x>=n || next.y< || next.y>=m || next.time<= || map[next.x][next.y]==) continue;
if (map[next.x][next.y]==){
ans=next.temp;
return ;
}
else if (map[next.x][next.y]==){
next.time=;
map[next.x][next.y]=;
}
Q.push(next);
}
}
return ;
}
int main(){
int t;
cin >> t;
while (t--){
cin >> n >> m;
for (int i=;i<n;i++){
for (int j=;j<m;j++){
cin >> map[i][j];
if (map[i][j]==){
start.x=i;
start.y=j;
start.temp=;
start.time=;
}
}
}
memset(V,,sizeof(V));
ans=;
if (bfs()) cout << ans << endl;
else cout << - << endl;
}
return ;
}