Description
Given a diagram of Farmer John's field, determine how many ponds he has.
Input
* 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
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
Hint
There are three ponds: one in the upper left, one in the lower left,and one along the right side.
#include<iostream>
#include <deque>
#include<stack>
#include<queue>
#include<math.h>
#include<algorithm>
#include<stdlib.h>
#include<string>
#include<stdio.h>
#include<string.h>
typedef long long LL;
#define $ 3.141592654
using namespace std;
char a[100][100];
int v[100][100]={0};
int m,n;
char f(int x,int y)//判断是否越界
{
if(x>=0&&x<m&&y>=0&&y<n)
return a[x][y];
return '.';
}
void DFS(int x,int y)
{
if(v[x][y]==0)
{
v[x][y]=1;
if(f(x-1,y-1)=='W')
DFS(x-1,y-1);
if(f(x-1,y)=='W')
DFS(x-1,y);
if(f(x-1,y+1)=='W')
DFS(x-1,y+1);
if(f(x,y-1)=='W')
DFS(x,y-1);
if(f(x,y+1)=='W')
DFS(x,y+1);
if(f(x+1,y-1)=='W')
DFS(x+1,y-1);
if(f(x+1,y)=='W')
DFS(x+1,y);
if(f(x+1,y+1)=='W')
DFS(x+1,y+1);
}
}
int main()
{
int i,j,k,ans=0;
scanf("%d%d",&m,&n);
getchar();
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
scanf("%c",&a[i][j]);
getchar();
}
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
if(v[i][j]==0&&a[i][j]=='W')
{
ans++;
DFS(i,j);//当此次调用函数完成时,与该‘W’相邻的所有‘W’都已经被标记了;遍历的时候就不会再满足“v[i][j]==0“这个条件
}}
}
printf("%d\n",ans);
return 0;
}