思路:
- BFS,记录联通块(实际就是记录经过几次BFS)。
代码:
#include <iostream>
#include <cstring>
#include <queue>
using namespace std;
const int maxn = 105;
const int moveto[8][2] = {1,0 , -1,0 , 0,1 , 0,-1 , -1,-1 , 1,1 , 1,-1 , -1,1};
bool mp [maxn][maxn];
bool vis[maxn][maxn];
int M,N;
struct grid{
int x,y;
grid (int x,int y) : x(x) , y(y) {} ;
};
queue<grid> Q;
int ans;
void init(){
memset(mp , false , sizeof(mp)) ;
memset(vis ,false , sizeof(vis));
while(Q.size())
Q.pop();
ans = 0;
return ;
}
void BFS(){
while(memcmp(vis , mp , sizeof(mp))){
ans++;
int stx,sty;
for(stx=1;stx<=M;stx++){
for(sty=1;sty<=N;sty++)
if(mp[stx][sty] && !vis[stx][sty])
break;
if(mp[stx][sty] && !vis[stx][sty])
break;
}
Q.push(grid(stx,sty));vis[stx][sty] = true;
while(Q.size()){
grid cur = Q.front() ; Q.pop() ;
int x = cur.x ; int y = cur.y ;
for(int i=0;i<8;i++){
int nx = x + moveto[i][0];
int ny = y + moveto[i][1];
if(nx < 1 || ny < 1 || nx > M || ny > N)
continue;
if(mp[nx][ny] && !vis[nx][ny]){
Q.push(grid(nx , ny));
vis[nx][ny] = true;
}
}
}
}
return ;
}
int main(){
while(cin>>M>>N && M){
init();
for(int i=1;i<=M;i++){
for(int j=1;j<=N;j++){
char te;
cin>>te;
if(te == '@')
mp[i][j] = true;
}
}
BFS();
cout<<ans<<endl;
}
return 0;
}