Lake Counting
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.
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<stdio.h> 2 #include<string.h> 3 #include<algorithm> 4 #include<stack> 5 #include<queue> 6 #include<deque> 7 #include<vector> 8 using namespace std; 9 char str[500][500],m,n; 10 void dfs(int x,int y) 11 { 12 int i,j; 13 str[x][y]='.'; 14 for(i=-1;i<=1;i++) 15 for(j=-1;j<=1;j++) 16 { 17 if(x+i>=0&&x+i<m&&y+j>=0&&y+j<n&&str[x+i][y+j]=='W') 18 dfs(x+i,y+j); 19 } 20 } 21 int main() 22 { 23 int i,j; 24 scanf("%d%d",&m,&n); 25 26 getchar(); 27 int ans=0; 28 for(i=0; i<m; i++) 29 scanf("%s",&str[i]); 30 for(i=0; i<m; i++) 31 for(j=0; j<n; j++) 32 { 33 if(str[i][j]=='W') 34 { 35 dfs(i,j); 36 ans++; 37 } 38 } 39 printf("%d\n",ans); 40 41 }
本文来自博客园,作者:左手边五十米,转载请注明原文链接:https://www.cnblogs.com/moomcake/p/8810916.html