给定的区域中有草方格和空方格,两个人任选草方格开始放火(可以选中同一个草方格),火每分钟向上下左右的草方格蔓延1格,空方格不会着火。放火的时刻为第0分钟。如果他们可以烧完所有草方格,输出所需时间;如果不能,输出-1.
#include<iostream>
#include<stdlib.h>
#include<time.h>
#include<algorithm>
#include<vector>
#include<set>
#include<queue>
#include<cstring>
#include<cstdio>
#include<string>
/*#define mem(a,b) memset(a,b,sizeof(a))
#define f(i,a,b) for(int i=a;i<=b;i++)
#define af(i,a,b) for(int i=a;i>=b;i--)
*/
using namespace std;
typedef long long LL;
const LL INF = 0x3f3f3f3f;
const int maxn = 100000 + 10;
int n, m;
int Map[15][15];
int cnt[15][15];
struct node {
int x, y;
};
int dx[] = { 0,0,1,-1 };
int dy[] = { 1,-1,0,0 };
queue<node> q;
int bfs(node t1, node t2) {
q.push(t1);
q.push(t2);
cnt[t1.x][t1.y] = 0;
cnt[t2.x][t2.y] = 0;
while (!q.empty()) {
node t = q.front();
q.pop();
for (int i = 0; i < 4; i++) {
int nx = t.x + dx[i];
int ny = t.y + dy[i];
if (!Map[nx][ny]) continue;
if (cnt[nx][ny] == INF) {
cnt[nx][ny] = cnt[t.x][t.y] + 1;
node nt; nt.x = nx; nt.y = ny;
q.push(nt);
}
}
if (q.empty()) {
int ok = 1;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
if (Map[i][j] && cnt[i][j] == INF) {
ok = 0;
break;
}
}
if (!ok) break;
}
if (ok) return cnt[t.x][t.y];
else return INF;
}
}
}
int main()
{
//ios::sync_with_stdio(false);
//int t; cin >> t; while (t--){
int t; cin >> t;
for(int k=1;k<=t;k++){
cout << "Case " << k << ": ";
memset(Map, 0, sizeof(Map));
memset(cnt, INF, sizeof(cnt));
int ans = INF;
while (!q.empty()) q.pop();
vector<node> v;
cin >> n >> m;
for (int i = 1; i <= n; i++) {
getchar();
for (int j = 1; j <= m; j++) {
char ch = getchar();
if (ch == '.') Map[i][j] = 0;
else {
Map[i][j] = 1;
node t;
t.x = i; t.y = j;
v.push_back(t);
}
}
}
node s1, s2;
int len = v.size();
for (int i = 0; i < len; i++) {
s1 = v[i];
for (int j = i; j < len; j++) {
s2 = v[j];
int ans_tmp = bfs(s1, s2);
ans = (ans_tmp < ans) ? ans_tmp : ans;
memset(cnt, INF, sizeof(cnt));
}
}
if (ans == INF) cout << -1;
else cout << ans;
cout << endl;
}
return 0;
}