HDU【1072】Nightmare

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1072
分析
这道题目涉及到bfs+回溯,所以不能像一般的bfs将经过的点进行标记,因为题目中炸弹的爆炸时长为6,所以只需要将经过的4的点进行标记,其他已经走过的点也只是在4这个点上最多回溯6步。

#include<iostream>
#include<cstdio>
#include<queue>
#include<algorithm>
using namespace std;
int a[10][10];
int n,m,ans;
int dir[][2] = {{-1,0},{1,0},{0,-1},{0,1}};
struct Node {
	int x,y,step,time;
	Node(int x,int y,int step,int time) {
		this->x = x;
		this->y = y;
		this->step = step;
		this->time = time;
	}
};
bool isValid(int x,int y)//判断这个点是否可以走
{
	return (x >= 0) && (x < n) && (y >= 0) && (y < m) && (a[x][y] != 0);
}
void bfs(int x,int y)
{
	queue<Node> q;
	q.push(Node(x,y,0,0));
	while(!q.empty()) {
		Node head = q.front();
		q.pop();
		for(int i = 0; i < 4; i++) {
			int nx = head.x + dir[i][0];
			int ny = head.y + dir[i][1];
			if(isValid(nx,ny)) {
				Node node(nx,ny,head.step + 1,head.time + 1);
				if(a[nx][ny] == 3 && node.time < 6) {
					ans = node.step;
					return;
				}
				if(node.time < 6) {//如果小于6,那么还可以加入队列中
					if(a[nx][ny] == 4) node.time = 0,a[nx][ny] = 0;//对4这个点进行标记,下次不再经过
					q.push(node);
				}
			}
		}
	}
}
int main()
{
	int T;
	scanf("%d",&T);
	while(T--) {
		scanf("%d%d",&n,&m);
		int x,y;
		for(int i = 0; i < n; i++)
			for(int j = 0; j < m; j++) {
				scanf("%d",&a[i][j]);
				if(a[i][j] == 2) x = i,y = j;
			}
		ans = 0;
		bfs(x,y);
		if(ans == 0) printf("-1\n");
		else printf("%d\n",ans);
	}
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值