Fire Game
#include<stdio.h>
#include<cstring>
#include<queue>
using namespace std;
#define maxn 222
#define inf 0x3f3f3f3f
int t,m,n,ans,flag,sum,total;
char mmp[maxn][maxn];
bool vis[maxn][maxn];
int to[5][3]= {{1,0},{0,1},{0,-1},{-1,0}};
vector<pair<int,int> >gra;
bool judge(int x,int y)
{
if(mmp[x][y]=='#'&&x>=0&&x<n&&y>=0&&y<m&&vis[x][y]==0)
return true;
return false;
}
struct node
{
int x,y,cnt;
} top1,top2,temp;
void bfs(int s1x,int s1y,int s2x,int s2y)
{
queue<node>q1;
q1.push((node)
{
s1x,s1y,0
});
q1.push((node)
{
s2x,s2y,0
});
vis[s1x][s1y]=vis[s2x][s2y]=1;
total=0;
while(!q1.empty())
{
if(!q1.empty())
{
top1=q1.front();
q1.pop();
total++;
}
if(total==sum)
{
ans=min(top1.cnt,ans);
return;
}
for(int i=0; i<4; i++)
{
temp.cnt=top1.cnt+1;
temp.x=top1.x+to[i][0];
temp.y=top1.y+to[i][1];
if(judge(temp.x,temp.y))
{
q1.push(temp);
vis[temp.x][temp.y]=1;
}
}
}
}
int main()
{
scanf("%d",&t);
for(int q=1; q<=t; q++)
{
flag=sum=0;
gra.clear();
scanf("%d%d",&n,&m);
for(int i=0; i<n; i++)
{
getchar();
for(int j=0; j<m; j++)
{
scanf("%c",&mmp[i][j]);
if(mmp[i][j]=='#')
{
sum++;
gra.push_back(make_pair(i,j));
}
}
}
printf("Case %d: ",q);
if(sum<3)
{
printf("0\n");
continue;
}
int len=gra.size();
ans=inf;
for(int i=0; i<len-1; i++)
for(int j=i+1; j<len; j++)
{
memset(vis,0,sizeof(vis));
bfs(gra[i].first,gra[i].second,gra[j].first,gra[j].second);
}
if(ans==inf)
printf("-1\n");
else
printf("%d\n",ans);
}
return 0;
}