Lake Counting
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.
译文:由于最近的降雨,水汇集在农民约翰的田地的不同地方,其由N×M(1 <= N <= 100; 1 <= M <= 100)的正方形矩形表示。每个方块包含水(‘W’)或旱地(’’)。农夫约翰想弄清楚他的田地里有多少个池塘。池塘是一组连接的正方形,其中有水,其中一个正方形被认为与其所有八个邻接地域相邻。
给出农夫约翰的田地图,确定他有多少池塘。
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.
译文:
第1行:两个以空格分隔的整数:N和M
第2~N + 1行:每行M个字符代表一行农民约翰的字段。每个字符都是’W’或’.’。字符之间没有空格。
Output
Line 1: The number of ponds in Farmer John’s field.
译文:第1行:农民约翰的田地里的池塘数量。
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.
译文:
输出细节:
有三个池塘:一个在左上角,一个在左下角,一个在右侧。
C++编写:
#include<iostream>
using namespace std;
const int MAX_N=100;
const int MAX_M=100;
char field[MAX_N][MAX_M+1]; //定义一个数组表示田地
int N,M;
void dfs(int x,int y)
{
field[x][y] = '.';
//循环遍历移动的8个方向
for(int dx=-1;dx<=1;dx++)
{
for(int dy=-1;dy<=1;dy++)
{
int nx = x+dx,ny = y+dy;
if(nx>=0 && nx<N && ny>=0 && ny<M && field[nx][ny] == 'W')
dfs(nx,ny);
}
}
}
void cal()
{
ios::sync_with_stdio(false);
int sum=0;
for(int i=0;i<N;i++)
{
for(int j=0;j<M;j++)
{
if(field[i][j] == 'W')
{
dfs(i,j);
sum++;
}
}
}
cout<<sum<<endl;
}
int main()
{
cin>>N>>M;
for(int i=0;i<N;i++)
{
for(int j=0;j<M;j++)
{
cin>>field[i][j];
}
}
cal();
return 0;
}