poj3268Lake Counting(8連通分量)
Lake Counting
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. Input * Line 1: Two space-separated integers: N and M Output * Line 1: The number of ponds in Farmer John's field. Sample Input Sample Output Hint OUTPUT DETAILS: Source |
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
int R,C;
int ans;
#define maxn 205
char gird[maxn][maxn];
void dfs(int r,int c)
{
if(r<0||r>=R||c<0||c>=C||gird[r][c]!='W')
return ;
gird[r][c]='.';
dfs(r,c+1);
dfs(r,c-1);
dfs(r+1,c);
dfs(r-1,c);
dfs(r+1,c+1);
dfs(r+1,c-1);
dfs(r-1,c-1);
dfs(r+1,c-1);
dfs(r-1,c+1);
}
int main()
{
while(~scanf("%d%d",&R,&C))
{ans=0;
for(int i=0;i<R;i++)
for(int j=0;j<C;j++)
scanf(" %c",&gird[i][j]);
for(int i=0;i<R;i++)
for(int j=0;j<C;j++)
if(gird[i][j]=='W')
{ans++;
dfs(i,j);
}
printf("%d\n",ans);
}
return 0;
}