Lake Counting

Posted #忘乎所以#

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Lake Counting相关的知识,希望对你有一定的参考价值。

Lake Counting
Time Limit: 1000MS   Memory Limit: 65536K
Total Submissions: 36946   Accepted: 18370

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

简单深搜一下,就差不多了.

 1 #include<iostream>
 2 #include<cstring>
 3 #include<cstdio>
 4 #include<algorithm>
 5 #define  N 105
 6 #define test cout<<"*****"<<endl
 7 using namespace std;
 8 char k[N][N];
 9 int n,m;
10 int dir[8][2]={{-1,-1},{-1,0},{-1,1},{0,1},{1,1},{1,0},{1,-1},{0,-1}};
11 void dfs(int x,int y){
12         k[x][y]=.;
13     for(int t=0;t<8;t++){
14             int xx=x+dir[t][0];
15             int yy=y+dir[t][1];
16             if(xx>=0&&xx<n&&yy>=0&&yy<m&&k[xx][yy]==W)
17                 dfs(xx,yy);
18     }
19 }
20 int main(){
21         int cnt=0;
22         cin>>n>>m;
23         for(int i=0;i<n;i++){
24             for(int j=0;j<m;j++){
25                 cin>>k[i][j];
26             }
27         }
28         for(int i=0;i<n;i++)
29             for(int j=0;j<m;j++){
30                 if(k[i][j]==W){
31                         dfs(i,j);
32                         cnt++;
33                     }
34             }
35         printf("%d\n",cnt);
36     return 0;
37 }

 

以上是关于Lake Counting的主要内容,如果未能解决你的问题,请参考以下文章

Lake Counting (DFS)

Lake Counting

Lake Counting

Lake Counting

Lake Counting

POJ 2386 Lake Counting