Lake Counting(POJ 2386)

Lake Counting
Time Limit: 1000MS   Memory Limit: 65536K
Total Submissions: 44751   Accepted: 22120

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

Hint

OUTPUT DETAILS: 

There are three ponds: one in the upper left, one in the lower left,and one along the right side.
 
  • 题解:从任意的'W'开始,不停地把邻接的部分用'.'代替,1次dfs后与初始的这个W连接的所有'W'就都被替换成了'.',因此直到图中不再存在w为止,总共进行dfs的次数就是答案了,复杂度是O(n*m)
  • 代码:
     1 #include <iostream>
     2 
     3 using namespace std;
     4 
     5 int n,m;
     6 char ** a;
     7 
     8 void dfs(int, int);
     9 
    10 int main()
    11 {
    12     cin >> n >> m;
    13     a = new char*[n];
    14     for (int i=0; i<n; i++) a[i]=new char[m];
    15     for (int i=0; i<n; i++)
    16     {
    17         for (int j=0; j<m; j++)
    18         {
    19             cin >> j[i[a]];
    20         }
    21     }
    22     int s=0;
    23     for (int i=0; i<n; i++)
    24     {
    25         for (int j=0; j<m; j++)
    26         {
    27             if (j[i[a]]=='W') 
    28             {
    29                 dfs(i,j);
    30                 ++s;
    31             }
    32         }
    33     }
    34     cout << s << endl;
    35 }
    36 
    37 void dfs(int x, int y)
    38 {
    39     y[x[a]] ='.';
    40     for (int dx=-1; dx<=1; dx++)
    41     {
    42         for (int dy=-1; dy<=1; dy++)
    43         {
    44             int xx=x+dx, yy=y+dy;
    45             if (xx>=0 && xx<n && yy>=0 && yy<m && yy[xx[a]]=='W') dfs(xx,yy);
    46         }
    47     }
    48 }
原文地址:https://www.cnblogs.com/Ymir-TaoMee/p/9408008.html