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.
w是水,看在这一个n*m的区域内有多少个池塘,一个位置与他周围八个相邻位置中的任意一个相连都算作一个池塘。
一个小问题:cin会去除空格和换行符,但是scanf %c会把空格和换行符都读入所以输入最好用scanf
#include<iostream>
using namespace std;
char lake[105][105];
int n,m;
void init(){
cin>>n>>m;
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
cin>>lake[i][j];
}
}
/*
scanf("%d%d",&n,&m);
getchar();
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
scanf("%c",&lake[i][j]);
}
getchar();
}
*/
}
void dfs(int i,int j){
if(i<0||i>=n||j<0||j>=m)
return ;
if(lake[i+1][j]=='W'){ //下
lake[i+1][j]='.';
dfs(i+1,j);
}
if(lake[i][j+1]=='W'){ //右
lake[i][j+1]='.';
dfs(i,j+1);
}
if(lake[i+1][j+1]=='W'){ //右下
lake[i+1][j+1]='.';
dfs(i+1,j+1);
}
if(lake[i-1][j+1]=='W'){ //左下
lake[i-1][j+1]='.';
dfs(i-1,j+1);
}
if(lake[i-1][j]=='W'){ //上
lake[i-1][j]='.';
dfs(i-1,j);
}
if(lake[i][j-1]=='W'){ //左
lake[i][j-1]='.';
dfs(i,j-1);
}
if(lake[i-1][j-1]=='W'){ //左上
lake[i-1][j-1]='.';
dfs(i-1,j-1);
}
if(lake[i+1][j-1]=='W'){ //右上
lake[i+1][j-1]='.';
dfs(i+1,j-1);
}
}
int main(){
ios::sync_with_stdio(false);cin.tie(0); //关闭缓冲流入口,加快cin读取
int count=0;
init();
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
if(lake[i][j]=='W'){
dfs( i , j);
count++;
}
}
}
cout<<count<<endl;
return 0;
}