题目:
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.
题目大意为:由于最近的降雨,在农夫约翰田地的不同地方积聚了水,用N x M(1 <= N <= 100; 1 <= M <= 100)正方形的矩形表示。每个方格包含水(‘W’)或旱地(’。’)。农夫约翰想弄清楚他的田地里形成了多少个池塘。池塘是一组相连的正方形,里面有水,其中一个正方形被认为与八个池塘相邻。给定农夫约翰的田野图,确定他有多少个池塘。
题解:我们可以先定义一个二维字符数组,等会用它来存地图;再定义一个等大的二位整型数组,用来表示是否已经收索。由题意知若水的周围八个位置只要有水就会连在一起,形成水塘。所以我们从地图第一个位置开始搜索,如果他没有水,就搜索下一个位置,如果有,就标记并计数,同时开始搜索他旁边的八个位置,如果有水,就标记,用递归来把连成水塘的都标记起来,并记录水塘的数量即可得到答案。
代码如下:
#include<iostream>
#include<algorithm>
#include<cstdio>
#include<cstring>
using namespace std;
char a[100][100];
int b[100][100];
int n, m;
int ans;
void DFS(int x,int y)
{
b[x][y]=1;
if(x+1<n&&a[x+1][y]=='W'&&b[x+1][y]==0) DFS(x+1,y);
if(y+1<m&&a[x][y+1]=='W'&&b[x][y+1]==0) DFS(x,y+1);
if(y+1<m&&x+1<n&&a[x+1][y+1]=='W'&&b[x+1][y+1]==0) DFS(x+1,y+1);
if(x-1>=0&&a[x-1][y]=='W'&&b[x-1][y]==0) DFS(x-1,y);
if(y-1>=0&&a[x][y-1]=='W'&&b[x][y-1]==0) DFS(x,y-1);
if(y-1>=0&&x-1>=0&&a[x-1][y-1]=='W'&&b[x-1][y-1]==0) DFS(x-1,y-1);
if(y-1>=0&&x+1<n&&a[x+1][y-1]=='W'&&b[x+1][y-1]==0) DFS(x+1,y-1);
if(y+1<m&&x-1>=0&&a[x-1][y+1]=='W'&&b[x-1][y+1]==0) DFS(x-1,y+1);
}
int main()
{
cin>>n>>m;
for(int i=0;i<n;i++)
cin>>a[i];
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
if(a[i][j]=='W'&&b[i][j]==0)
{
ans++;
b[i][j]=1;
DFS(i,j);
}
}
}
cout<<ans;
return 0;
}