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;
		}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值