Description
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. InputLine 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.
Sample Input 10 12 w…ww. .www…www …ww…ww. …ww. …w… …w…w… .w.w…ww.
w.w.w…w. .w.w…w. …w…w. Sample Output 3
题目大意:
给你一副图,其中’W’代表池塘,’.'代表土地,问现在这幅图中有多少个池塘,如果一个池塘的八个方向上如果有池塘,则只算一个,类似于连通块。
#include<iostream>
#include<queue>
using namespace std;
char mapp[110][110];
int dir[8][2]={{0,1},{0,-1},{-1,0},{1,0},{-1,-1},{-1,1},{1,-1},{1,1}};
struct node
{
int x,y;
};
queue<node> q;
node now;
void BFS(int i,int j)
{
while(!q.empty())
{
now=q.front();
q.pop();
for(int k=0;k<8;k++)
{
node next;
next.x=now.x+dir[k][0];
next.y=now.y+dir[k][1];
if(mapp[next.x][next.y]=='W')
{
q.push(next);
mapp[next.x][next.y]='*';
}
}
}
}
int main()
{
int N,M,len=0;
while(cin>>N>>M)
{
for(int i=1;i<=N;i++)
{
for(int j=1;j<=M;j++)
{
cin>>mapp[i][j];
}
}
for(int i=1;i<=N;i++)
{
for(int j=1;j<=M;j++)
{
if(mapp[i][j]=='W')
{
len++;
now.x=i;
now.y=j;
q.push(now);
mapp[now.x][now.y]='*';
BFS(i,j);
}
}
}
cout<<len<<endl;
}
}