HDU1072-Nightmare(BFS)

题目链接:传送门Biubiubiu~~

分析:题意大概是给一个迷宫,2是起点,3是终点,炸弹时间6秒,而达到4后炸弹时间重置,达到0秒时重置炸弹无效和到达终点无效,本题一个坑点也是我一开始没攻破的地方就是一个地方可以多次走,这样的话就极有可能陷入无限死循环,队列排不完的情况,因为数据比较小,所以只要把4走过之后变成1就好啦,最后所有队列都会消失~~

AC代码:

#include<iostream>
#include<cstring>
#include<queue>
using namespace std;
struct node{
	int x,y,times,step; //坐标,以及炸弹剩余时间,以及步数
};
int n,m;
node s,e;
int d[4][2]={{1,0},{-1,0},{0,1},{0,-1}};
int maze[10][10];
bool check(int x,int y){
	if(x>=0&&x<n&&y>=0&&y<m)	return true;
	else return false;
}
int bfs(){
	queue<node>	que;
	que.push(s);
	while(!que.empty()){
		node next;
		node now=que.front();
		que.pop();
		
		if(maze[now.x][now.y]==3&&now.times!=0)	return now.step;
		if(now.times==1)	continue; //当秒数为1时后面无论怎么走都无效,所以这里直接继续循环
		
		for(int i=0;i<4;i++){
			next.x=now.x+d[i][0];	
			next.y=now.y+d[i][1];	
			next.times=now.times-1;	
			next.step=now.step+1;
			if(check(next.x,next.y)&&maze[next.x][next.y]!=0){
				if(maze[next.x][next.y]==4){	//当达到4时重置
					maze[next.x][next.y]=1;	//把重置炸弹点变为普通路
					next.times=6;	
					que.push(next);
				}
				else que.push(next);
			}
		}
	}
		return 0; 
}
int main(){
		int t;
		cin>>t;
		while(t--){
			cin>>n>>m;
			for(int i=0;i<n;i++){
				for(int j=0;j<m;j++){
					cin>>maze[i][j];
					if(maze[i][j]==2){
					s.x=i;	s.y=j;	s.times=6;	s.step=0; 
					}
				}
			}
			int total=bfs();
			if(total!=0)	cout<<total<<endl;
			else cout<<"-1"<<endl;
		}
}

猜你喜欢

转载自blog.csdn.net/weixin_43556295/article/details/88320181