http://acm.fzu.edu.cn/problem.php?pid=2150
#include <iostream> #include <algorithm> #include <math.h> #include <stdio.h> #include <queue> #include <vector> #include <cstring> using namespace std; #define inf 0x3f3f3f3f #define MAXN 22 char mmp[MAXN][MAXN]; bool vis[MAXN][MAXN]; int n,m; int to[4][2]= {0,1,0,-1,1,0,-1,0}; struct node { int x,y; int step; } temp; vector<node>fire; void init() { fire.clear(); memset(vis,0,sizeof(vis)); } bool judge() { for(int i=0; i<fire.size(); i++) if(vis[fire[i].x][fire[i].y]==0) return false; return true; } bool think(int x,int y) { if(x>=0&&y>=0&&x<n&&y<m&&!vis[x][y]&&mmp[x][y]=='#') return 1; return 0; } int bfs(node a,node b) { memset(vis,false,sizeof vis); int cnt=0; queue<node>q; q.push(a); q.push(b); vis[a.x][a.y]=1; vis[b.x][b.y]=1; while(!q.empty()) { cnt=max(cnt,q.front().step); for(int i=0; i<4; i++) { node tmp; tmp.x=q.front().x+to[i][0]; tmp.y=q.front().y+to[i][1]; tmp.step=q.front().step+1; if(think(tmp.x,tmp.y)) { vis[tmp.x][tmp.y]=1; q.push(tmp); } } q.pop(); } return cnt; } int main() { int t,ans; cin>>t; for(int cas=1; cas<=t; cas++) { init(); ans=inf; cin>>n>>m; for(int i=0; i<n; i++) for(int j=0; j<m; j++) { cin>>mmp[i][j]; if(mmp[i][j]=='#') { temp.x=i; temp.y=j; temp.step=0; fire.push_back(temp); } } for(int i=0; i<fire.size(); i++) for(int j=i; j<fire.size(); j++) { int small=bfs(fire[i],fire[j]); if(judge()) ans=min(small,ans); } printf("Case %d: ",cas); if(ans==inf) cout<<-1<<endl; else cout<<ans<<endl; } return 0; }