Lake Counting --POJ 2386
Posted bravewtz
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Lake Counting --POJ 2386相关的知识,希望对你有一定的参考价值。
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.
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.
* 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的主要内容,如果未能解决你的问题,请参考以下文章