POJ 2386 Lake Counting_steven 解题心得

原题:

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.

 

 
 
我的代码:
 1 #include<iostream>

 2 #include<cstdio>

 3 

 4 using namespace std;

 5 int flag = 1;

 6 char ground[110][110];

 7 int tree[110][110];

 8 int square = 0;

 9 int directionX[8] = {1 ,  1 ,  1 ,   0,    0 ,    -1,   -1 , -1 };

10 int directionY[8] = { 1,  0 ,  -1,   1,    -1,    1,    0,   -1 };

11 int n, m;

12 

13 void dfs(int i,int j ,int sq)

14 {

15     if (ground[i][j] == 'W'&&tree[i][j] == 0)

16     {

17         tree[i][j] = sq;

18         //拓展

19         for (int k = 0; k < 8; k++)

20         {

21             if (i + directionX[k] >= n || j + directionY[k] >= m ||

22                 i + directionX[k] < 0 || j + directionY[k] < 0)            //越界

23                     {continue;}

24             else

25             {

26                 dfs(i + directionX[k], j + directionY[k], sq);

27             }

28         }

29     }

30     return;

31 }

32 

33 

34 int main()

35 {

36     

37     cin >> n>>m;

38     for (int i = 0; i < n; i++)

39         scanf("%s", ground[i]);

40     for (int i = 0; i < n; i++)

41     {

42         for (int j = 0; j < m; j++)

43         {

44             if (ground[i][j] == 'W'&&tree[i][j] == 0)

45             {

46                 dfs(i, j, ++square);

47             }

48         }

49     }

50     cout << square << endl;

51 

52     return 0;

53 }

 

你可能感兴趣的:(count)