KuangBin 专题一:简单搜索 Fire Game

题目链接:
传送门

#include<cstdio>
#include<queue>
#include<cstring>
#include<algorithm>
using namespace std;
const int N = 15;
const int INF = 0x3f3f3f3f;
char theMap[N][N];
bool used[N][N],checked[N][N][N][N];
int ans, sum, sx1, sy1, sx2, sy2, n, m, mark, burned, ca, op[4][2]= {{0,1},{1,0},{0,-1},{-1,0}};

struct node {
	int x, y;
	int step;
} p1,p2;

void BFS() {
	//重新初始化used
	memset(used, 0, sizeof(used));
	queue <node> q;
	sum = 0;
	//标记为已读
	used[sx1][sy1] = 1;
	used[sx2][sy2] = 1;
	p1.x = sx1;
	p1.y = sy1;
	p1.step = 0;
	p2.x = sx2;
	p2.y = sy2;
	p2.step = 0;
	q.push(p1);
	q.push(p2);
	while(!q.empty()) {
		node cur, next;
		cur = q.front();
		q.pop();
		for(int i = 0; i < 4; i++) {
			next.x = cur.x + op[i][0];
			next.y = cur.y + op[i][1];
			//判断是否在边界内和是否被搜过
			if( 0 <= next.x && next.x < n && 0 <= next.y && next.y < m && theMap[next.x][next.y] == '#' && !used[next.x][next.y]) {
				used[next.x][next.y] = 1;
				next.step =  cur.step + 1;
				burned++;
				q.push(next);
			}
		}
		//记录下步数
		sum = max(sum, cur.step);
	}
}
int main() {
	int t;
	scanf("%d", &t);
	while(t--) {
		//初始化已被作为起始点的点
		memset(checked, 0, sizeof(checked));
		ans = INF;
		mark = 0;
		scanf("%d %d", &n, &m);
		for(int i = 0; i < n; i++) {
			scanf("%s", &theMap[i]);
			for(int j = 0; j < m; j++)
				if(theMap[i][j] == '#')
					mark++;
		}
		//特殊处理1
		if(mark <= 2) {
			printf("Case %d: 0\n", ++ca);
			continue;
		}
		//枚举两个起点
		for(int i1 = 0; i1 < n; i1++) {
			for(int j1 = 0; j1 < m; j1++) {
				if(theMap[i1][j1] == '#') {
					for(int i2 = 0; i2 < n; i2++) {
						for(int j2 = 0; j2 < m; j2++) {
							if(theMap[i2][j2] == '#' && (i1 != i2 || j1 != j2) && checked[i1][j1][i2][j2]==0) {
								checked[i1][j1][i2][j2] = 1;
								checked[i2][j2][i1][j1] = 1;
								sx1 = i1;
								sy1 = j1;
								sx2 = i2;
								sy2 = j2;
								burned = 2;
								BFS();
								if(ans > sum && mark == burned) {
									ans = sum;
								}
							}
						}
					}
				}
			}
		}
		if(ans == INF)
			printf("Case %d: -1\n", ++ca);
		else
			printf("Case %d: %d\n", ++ca, ans);
	}
	return 0;
}

注:我看的Description为: 911916648版本
这道是一道BFS题这道题感觉难点在于优化。一开始我超时了很多次,后来才做出来的。这道题本身思路很简单,就是从两个点出发,一直往外燃烧,看看最后烧完的堆数是否与与草的总堆数相等,不相等则说明没烧完,不对ans进行处理。相等则记录下来,以此类推找到耗时最少的方法。
这道题的主要优化有三点:
1.scanf的同时就统计’#'的个数
2.不必讨论连个点重合的情况因为两个点重合一定不及两个点分烧的快
3.两个点是没有先后顺序之分,比如a点为(1,2)b点为(4,5)和a点为(4,5)b点为(1,2)结果是一样的,所以没必要重复搜索。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值