D - Lake Counting

时间:2021-01-08 04:01:25

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.

Input

  • Line 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

Hint

OUTPUT DETAILS:

There are three ponds: one in the upper left, one in the lower left,and one along the right side.

搜索水题,只要往四周一直搜,搜过的改变值就可以,能搜几次就是几个;

#include<iostream>
#include<stdio.h>
#include<stdlib.h>
#include <iomanip>
#include<cmath>
#include<float.h>
#include<string.h>
#include<algorithm>
#define sf scanf
#define pf printf
#define pb push_back
#define mm(x,b) memset((x),(b),sizeof(x))
#include<vector>
#include<map>
#define rep(i,a,n) for (int i=a;i<n;i++)
#define per(i,a,n) for (int i=a;i>=n;i--)
typedef long long ll;
typedef long double ld;
typedef double db;
const ll mod=1e12+100;
const db e=exp(1);
using namespace std;
const double pi=acos(-1.0); char a[105][105]; bool dfs(int x,int y)
{
// cout<<x<<" "<<y<<endl; if(a[x][y]!='W') return false;
a[x][y]='a';//把经过的位置改变 if(a[x-1][y-1]=='W')//左上
dfs(x-1,y-1);
if(a[x-1][y+1]=='W')//右上
dfs(x-1,y+1);
if(a[x+1][y-1]=='W')//左下
dfs(x+1,y-1);
if(a[x+1][y+1]=='W')//右下
dfs(x+1,y+1);
if(a[x-1][y]=='W')//上
dfs(x-1,y);
if(a[x][y-1]=='W')//左
dfs(x,y-1);
if(a[x][y+1]=='W')//右
dfs(x,y+1);
if(a[x+1][y]=='W')//下
dfs(x+1,y);
return true;
}
int solve(int n,int m)
{
int sum=0;
rep(i,1,n+1)
{
rep(j,1,m+1)
if(dfs(i,j))
sum++;
}
return sum;
}
int main()
{
int n,m;
sf("%d%d%d%d",&n,&m);
mm(a,'.');
rep(i,1,n+1)
{
sf("%s",&a[i][1]);
//pf("1%s\n",&d[i]);
a[i][m+1]='.';
}
pf("%d\n",solve(n,m));
}