Description
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‘开始,不停地把邻接的部分用‘.‘代替。一次DFS后与初始的这个‘W‘连接的所有‘W‘就被替换成了‘.‘,因此直到图中不再存在‘W‘为止,总共进行的DFS的次数就是最终答案。
AC代码:
1 #include<iostream>
2 #include<cstdio>
3 using namespace std;
4 const int maxn=105;
5 int n,m,res;char mp[maxn][maxn];
6 void dfs(int x,int y){
7 mp[x][y]=‘.‘;
8 for(int dx=-1;dx<=1;++dx){
9 for(int dy=-1;dy<=1;++dy){
10 int nx=x+dx,ny=y+dy;
11 if(0<=nx && nx<n && 0<=ny && ny<m && mp[nx][ny]==‘W‘)dfs(nx,ny);//往8个方向寻找‘W‘的点
12 }
13 }
14 return;
15 }
16 int main(){
17 while(~scanf("%d%d",&n,&m)){
18 for(int i=0;i<n;++i){
19 getchar();
20 for(int j=0;j<m;++j)
21 scanf("%c",&mp[i][j]);
22 }
23 res=0;
24 for(int i=0;i<n;++i)
25 for(int j=0;j<m;++j)
26 if(mp[i][j]==‘W‘){dfs(i,j);res++;}
27 printf("%d\n",res);
28 }
29 return 0;
30 }
题解报告:poj 2386 Lake Counting
原文:https://www.cnblogs.com/acgoto/p/9302359.html