1 //枚举+BFS 2 #include<iostream> 3 #include<cstdio> 4 #include<algorithm> 5 #include<cmath> 6 #include<cstring> 7 #include<queue> 8 using namespace std; 9 10 #define INF 0xfffffff 11 12 int T,N,M,len; 13 char grid[15][15]; 14 15 struct Point 16 { 17 int x,y; 18 int times; 19 }point[105]; 20 21 Point p1,p2; 22 int ans; 23 bool book[15][15]; 24 25 bool isValid(int x,int y) 26 { 27 if(x<0 || x>=N || y<0 || y>=M || grid[x][y]!='#' || book[x][y]) 28 return false; 29 return true; 30 } 31 int dir[8]={0,1,0,-1, 1,0,-1,0}; 32 queue<Point> que1; 33 34 int BFS() 35 { 36 int counter=1,time=0; 37 Point tp1,tp2; 38 memset(book,false,sizeof(book)); 39 que1.push(p1); 40 book[p1.x][p1.y]=true; 41 42 if(p1.x!=p2.x || p1.y!=p2.y)//起点不同 43 { 44 que1.push(p2); 45 ++counter; 46 book[p2.x][p2.y]=true; 47 } 48 49 while(!que1.empty()) 50 { 51 if(!que1.empty()) 52 { 53 tp1=que1.front(); 54 for(int i=0;i<8;i+=2) 55 { 56 if(isValid(tp1.x+dir[i], tp1.y+dir[i+1])) 57 { 58 tp2.times=tp1.times+1; 59 tp2.x=tp1.x+dir[i]; 60 tp2.y=tp1.y+dir[i+1]; 61 que1.push(tp2); 62 63 time=tp2.times; 64 book[tp2.x][tp2.y]=true; ++counter; 65 } 66 } 67 que1.pop(); 68 } 69 70 } 71 if(counter < len) 72 return -1; 73 return time; 74 } 75 76 int main() 77 { 78 scanf("%d",&T); 79 int cnt = 0; 80 while(T--) 81 { 82 cnt++; 83 len=0; ans=INF; 84 scanf("%d%d",&N,&M); 85 for(int i=0;i<N;i++) 86 scanf("%s",grid[i]); 87 88 for(int i=0;i<N;i++) 89 for(int j=0;j<M;j++) 90 { 91 if(grid[i][j]=='#') 92 { 93 point[len].x=i; point[len].y=j; point[len++].times=0; 94 } 95 } 96 97 //枚举每次点燃两个草地的位置 98 for(int i=0;i<len;i++) 99 { 100 p1=point[i]; 101 for(int j=0;j<len;j++) 102 { 103 { 104 p2=point[j]; 105 int tans=BFS(); 106 if(tans!=-1) 107 ans=min(ans,tans); 108 } 109 } 110 if(ans == INF) 111 ans = -1; 112 printf("Case %d: %d ",cnt,ans); 113 } 114 return 0; 115 }