I - Fire Game

题目: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;
}
上一篇:在VectorCAST for Linux中使用分类树功能生成测试用例


下一篇:Python-迭代器