码迷,mamicode.com
首页 > 其他好文 > 详细

Lake Counting --POJ 2386

时间:2019-03-27 00:20:59      阅读:291      评论:0      收藏:0      [点我收藏+]

标签:...   field   std   pool   ike   algo   pre   for   john   

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

 1 #include<iostream>
 2 #include<cstdio>
 3 #include<cstring>
 4 #include<algorithm>
 5 using namespace std;
 6 const int maxn = 1e2+10;
 7 char a[maxn][maxn];
 8 int cnt=0;
 9 int n,m;
10 
11 void DFS(int i,int j){
12     for( int p=-1; p<=1; p++ ){
13         for( int q=-1; q<=1; q++ ){
14             int x=i+p;
15             int y=j+q;
16             if(x>=0&&x<=n-1&&y>=0&&y<=m-1&&a[x][y]==W){
17                 a[x][y]=.;
18                 DFS(x,y);
19             }
20         }
21     }
22 }
23 
24 int main(){
25     while(~scanf("%d%d",&n,&m)&&n&&m){
26         memset(a,0,sizeof(a));
27         cnt=0;
28         for( int i=0; i<n; i++ ){
29             scanf("%s",a[i]);
30         }
31         for( int i=0; i<n; i++){
32             for( int j=0; j<m; j++ ){
33                 if(a[i][j]==W){
34                     cnt++;
35                     DFS(i,j);
36                 }
37             }
38         }
39         printf("%d\n",cnt);
40     }
41     return 0;
42 }

 

Lake Counting --POJ 2386

标签:...   field   std   pool   ike   algo   pre   for   john   

原文地址:https://www.cnblogs.com/Bravewtz/p/10604735.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!