思路:
代码:
#include <iostream>
#include <vector>
#include <queue>
#include <cstring>
#define INF 0x3f3f3f3f
using namespace std;
const int maxn = 15;
const int moveto[4][2] = {1,0 , -1,0 , 0,1 , 0,-1};
bool mp [maxn][maxn];
bool vis[maxn][maxn];
int M,N;
int ans;
struct pt{
int x,y;
int step;
pt(int x,int y,int step) : x(x) , y(y) , step(step) {} ;
};
vector<pt> V;
queue<pt> Q;
void bfs(pt a , pt b){
memset(vis , false , sizeof(vis));
int curans = 0;
Q.push(a);
Q.push(b);
vis[a.x][a.y] = vis[b.x][b.y] = true;
while(!Q.empty()){
pt cur = Q.front() ; Q.pop();
int x = cur.x;
int y = cur.y;
for(int i=0;i<4;i++){
int nx = x + moveto[i][0];
int ny = y + moveto[i][1];
if(!mp[nx][ny])
continue;
if(vis[nx][ny])
continue;
vis[nx][ny] = true;
Q.push(pt(nx , ny , cur.step + 1));
curans = cur.step + 1;
}
}
for(int i=1;i<=M;i++)
for(int j=1;j<=N;j++)
if(mp[i][j] != vis[i][j])
return;
ans = ans > curans ? curans : ans;
return ;
}
int main(){
int T;cin>>T;
for(int t=1;t<=T;t++){
V.clear();
memset(mp , false , sizeof(mp));
ans = INF;
cin>>M>>N;
for(int i=1;i<=M;i++)
for(int j=1;j<=N;j++){
char temp;
cin>>temp;
mp[i][j] = temp == '#' ? true : false;
if(mp[i][j])
V.push_back(pt(i,j,0));
}
for(vector<pt>::iterator i = V.begin() ; i != V.end() ; i++)
for(vector<pt>::iterator j = i ; j != V.end() ; j++)
bfs(*i , *j);
if(ans == INF)
ans = -1;
cout<<"Case "<<t<<": "<<ans<<endl;
}
return 0;
}