## POJ-2386

POJ-2386

Due to recent rains, water has pooled in various places in Farmer John’s field, which is represented by a rectangle of N x M (1 <= N <= 100; 1 <= M <= 100) squares. Each square contains either water (‘W’) or dry land (’.’). Farmer John would like to figure out how many ponds have formed in his field. A pond is a connected set of squares with water in them, where a square is considered adjacent to all eight of its neighbors.

Given a diagram of Farmer John’s field, determine how many ponds he has.
Input

• Line 1: Two space-separated integers: N and M

• Lines 2…N+1: M characters per line representing one row of Farmer John’s field. Each character is either ‘W’ or ‘.’. The characters do not have spaces between them.
Output

• Line 1: The number of ponds in Farmer John’s field.
题目大意
有一个N*M的矩阵,每个格子上为’W’或’.’。求连通块的个数。（八个方向）
解题思路
用搜索将连通块标记,搜索的次数即为联通块的个数。
代码实现

``````#include <cstdio>
#include <iostream>
#include <queue>
using namespace std;
int dx[]={0,0,1,-1,1,1,-1,-1};
int dy[]={1,-1,0,0,1,-1,1,-1};
queue <int> X,Y;
bool sym;
int a;
int n,m;
void BFS(int xxx,int yyy)
{
X.push(xxx);
Y.push(yyy);
sym[xxx][yyy]=true;
while (!X.empty())
{
int x=X.front();
int y=Y.front();
X.pop();Y.pop();
for (int i=0;i<8;i++)
{
int xx=x+dx[i];
int yy=y+dy[i];
if (xx<1 || xx>n || yy<1 || yy>m || sym[xx][yy] || a[x][y]!=1) continue;
sym[xx][yy]=true;
X.push(xx);
Y.push(yy);
}
}

}
int main()
{
scanf("%d%d",&n,&m);
for (int i=1;i<=n;i++)
for (int j=1;j<=m;j++)
{
char ch;
cin>>ch;
if (ch=='W') a[i][j]=1;
}
int ans=0;
for (int i=1;i<=n;i++)
for (int j=1;j<=m;j++)
if (a[i][j]==1 && !sym[i][j])
{
BFS(i,j);
ans++;
}
printf("%d\n",ans);
}
``````