宽度优先搜索算法(又称广度优先搜索)是最简便的图的搜索算法之一,这一算法也是很多重要的图的算法的原型。Dijkstra单源最短路径算法和Prim最小生成树算法都采用了和宽度优先搜索类似的思想。其别名又叫BFS,属于一种盲目搜寻法,目的是系统地展开并检查图中的所有节点,以找寻结果。换句话说,它并不考虑结果的可能位置,彻底地搜索整张图,直到找到结果为止。
#include<cstdio>
#include<queue>
#include<cstring>
#include<algorithm>
using namespace std;
const int MAX = 1e2 + 10;
typedef long long LL;
char s[MAX][MAX];
int n,m,vis[MAX][MAX],ans;
int fx[8] = {0,0,-1,1,-1,1,-1,1},fy[8] = {-1,1,0,0,-1,-1,1,1};
struct node
{
int x,y;
};
void bfs(int x,int y)
{
vis[x][y] = 1;
queue <node> q;
node o;
o.x = x,o.y = y;
q.push(o);
while(!q.empty())
{
o = q.front();
q.pop();
for(int i = 0; i < 8; i++)
{
int xx = o.x + fx[i],yy = o.y + fy[i];
if(xx >= 0 && yy >= 0 && xx < n && yy < m && !vis[xx][yy] && s[xx][yy] == '@')
{
node w;
vis[xx][yy] = 1;
w.x = xx,w.y = yy;
q.push(w);
}
}
}
}
int main()
{
while(~scanf("%d %d",&n,&m),m)
{
memset(vis,0,sizeof(vis));
for(int i = 0; i < n; i++)
scanf("%s",s[i]);
ans = 0;
for(int i = 0; i < n; i++)
for(int j = 0; j < m; j++)
if(!vis[i][j] && s[i][j] == '@')
ans++,bfs(i,j);
printf("%d\n",ans);
}
return 0;
}