Lake Counting
Posted mzchuan
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Lake Counting相关的知识,希望对你有一定的参考价值。
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
百度翻译:由于最近的降雨,水聚集在农民约翰农场的各个地方,由一个n x m(1<=n<=100;1<=m<=100)的矩形表示。每个广场都有水(“W”)或旱地(“.”)。农夫约翰想知道他田里形成了多少池塘。池塘是一组相连的正方形,
其中有水,一个正方形被认为是邻近八个邻居。
思路:循环农场,找到水后将与之相连的水全部抽出,用dfs搜索,计算要抽几次。注意水是可以斜着连的。
1 #include <iostream> 2 #include <cstdio> 3 #include <fstream> 4 #include <algorithm> 5 #include <cmath> 6 #include <deque> 7 #include <vector> 8 #include <queue> 9 #include <string> 10 #include <cstring> 11 #include <map> 12 #include <stack> 13 #include <set> 14 #include <sstream> 15 #define mod 1000000007 16 #define eps 1e-6 17 #define ll long long 18 #define INF 0x3f3f3f3f 19 using namespace std; 20 21 int m,n; 22 string ct[100]; 23 int fx[8]=1,-1,0,0,1,1,-1,-1,fy[8]=0,0,1,-1,-1,1,-1,1; 24 void dfs(int i,int j) 25 26 ct[i][j]=‘.‘; 27 for(int k=0;k<8;k++) 28 29 int x=i+fx[k]; 30 int y=j+fy[k]; 31 if(x>=0&&x<m&&y>=0&&y<n&&ct[x][y]==‘W‘) 32 33 dfs(x,y); 34 35 36 37 38 int main() 39 40 scanf("%d %d",&m,&n); 41 for(int i=0;i<m;i++)//用string存放数据比较方便 42 43 cin>>ct[i]; 44 45 int ans=0;//计数器 46 for(int i=0;i<m;i++) 47 48 for(int j=0;j<n;j++) 49 50 if(ct[i][j]==‘W‘)//找到第一个水后将与之相连的水都 51 //抽出来 52 dfs(i,j); 53 ans++; 54 55 56 57 printf("%d",ans); 58
以上是关于Lake Counting的主要内容,如果未能解决你的问题,请参考以下文章