I - Fire Game

19 篇文章 0 订阅
15 篇文章 0 订阅

题目:I - Fire Game
思路:多源BFS

#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++;
		}
		if(mark == 0) {
		    printf("Case %d: -1\n", ++ca);
		    continue;
		}
		//特殊处理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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值