题解报告:poj 2386 Lake Counting(dfs求最大连通块的个数)

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)scanf("%s",mp[i]);
19         res=0;
20         for(int i=0;i<n;++i)
21             for(int j=0;j<m;++j)
22                 if(mp[i][j]=='W'){dfs(i,j);res++;}
23         printf("%d\n",res);
24     }
25     return 0;
26 }

 

posted @ 2018-07-12 22:56  霜雪千年  阅读(250)  评论(0编辑  收藏  举报