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.
题意:大小为N*M的园子下雨积水,八连通的积水被认为是连接在一起的,请问园子里一共有多少水洼。
题解:题目要求的就是W一共有多少块。找到一个W就开始DFS,然后将其变为'.'。搜索八个方向就可以了。
#include<iostream>
#include<cstring>
#include<cstdlib>
#include<cstdio>
using namespace std;
char a[101][101];
int n,m;
void dfs(int x,int y)
{
a[x][y]='.';
for(int i=-1;i<=1;i++)
for(int j=-1;j<=1;j++)
{
int nx=x+i;
int ny=y+j;
if(nx>0&&ny>0&&nx<=n&&ny<=m&&a[nx][ny]=='W')
{
dfs(nx,ny);
}
}
return ;
}
int main()
{
int ans;
while(cin>>n>>m)
{
ans=0;
for(int i=1;i<=n;i++)
for(int j=1;j<=m;j++)
cin>>a[i][j];
for(int i=1;i<=n;i++)
for(int j=1;j<=m;j++)
{
if(a[i][j]=='W')
{
dfs(i,j);
ans++;
}
}
cout<<ans<<endl;
}
}