给一块地,有的格子有草,有的是空地,草着火时会蔓延到相邻的草地,选两个点纵火,使整块地的所有草着火速度最快。
直接枚举选中的两块草地进行bfs,queue队列初始有两个点,依次bfs,用vis数组标记到达所有点的最小步数,对每种选择更新ans。
AC代码:
#include<cstdio>
#include<queue>
#include<vector>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<map>
using namespace std;
typedef pair<int,int> P;
typedef long long LL;
const int INF=0x3f3f3f3f,MAXN=1000000000+7;
int T,vis[15][15]={-1},mod[1000000],cnt=1,row[15],m,n,ans=INF;
int dr[]={-1,1,0,0},dc[]={0,0,-1,1};
char pic[15][15];
vector<pair<int,int> > N;
void bfs(P a,P b){
queue<P> que;
que.push(a); que.push(b);
vis[a.first][a.second]=0,vis[b.first][b.second]=0;
while (!que.empty()){
P t=que.front();que.pop();
int r=t.first,c=t.second;
for (int i=0;i<4;i++){
int nr=r+dr[i],nc=c+dc[i];
if (pic[nr][nc]=='#'&&vis[nr][nc]==-1&&nr>=1&&nr<=n&&nc>=1&&nc<=m){
que.push(make_pair(nr,nc));
vis[nr][nc]=vis[r][c]+1;
}
}
}
}
bool judge(int& d){
d=0;
for (int r=1;r<=n;r++){
for (int c=1;c<=m;c++){
if (vis[r][c]==-1&&pic[r][c]=='#')return false;
if (pic[r][c]=='#') d=max(d,vis[r][c]);
}
}
return true;
}
int main(){
scanf("%d",&T);
while (T--){
scanf("%d%d",&n,&m);
ans=INF;
N.clear();
for (int i = 1; i <=n; ++i) {
for (int j = 1; j <=m; ++j) {
scanf(" %c",&pic[i][j]);
if (pic[i][j]=='#') N.push_back(make_pair(i,j));
}
}
for (int i=0;i<N.size();i++){
for (int j=0;j<N.size();j++){
P a=N[i],b=N[j];
fill(vis[0],vis[0]+15*15,-1);
bfs(a,b);
int t;
if (judge(t)) {
ans=min(ans,t);
}
}
}
if (ans==INF) printf("Case %d: %d\n",cnt++,-1);
else printf("Case %d: %d\n",cnt++,ans);
}
}