Given a diagram of Farmer John's field, determine how many ponds he has.
* 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.
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
3Hint
There are three ponds: one in the upper left, one in the lower left,and one along the right side.
代码:
#include<stdio.h>
#include<string>
#include<string.h>
#include<iostream>
using namespace std;
char s[102][102];
void dfs(int p,int q)
{
int ii,jj;
if(s[p][q]=='.') return;
s[p][q]='.';
for(ii=-1;ii<2;ii++)
for(jj=-1;jj<2;jj++)
{
if(s[p+ii][q+jj]=='W')
{
dfs(p+ii,q+jj);
}
}
}
int main()
{
int m,n,i,j,k,sum=0;
scanf("%d %d",&m,&n);
getchar();
for(i=1;i<=m;i++)
{
for(j=1;j<=n;j++)
scanf("%c",&s[i][j]);
getchar(); //第一次交题漏了
}
for(i=1;i<=m;i++)
for(j=1;j<=n;j++)
{
if(s[i][j]=='W')
{
dfs(i,j);
sum++;
}
}
printf("%d\n",sum);
return 0;
}