poj2386 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.

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表示积水,积水周围8块有一块有积水就说明是联通的
问你总共有几块积水块?
代码如下:
 1 #include <cstdio>
 2 #include <cstdlib>
 3 #include <cstring>
 4 #include <iostream>
 5 using namespace std;
 6 int dis[][2] = {{0,1},{0,-1},{1,1},{1,-1},{1,0},{-1,0},{-1,1},{-1,-1}};
 7 
 8 int n,m;
 9 char map[102][102];
10 
11 void dfs(int x, int y) {
12     map[x][y] = '.';
13     for(int i = 0; i < 8; i++) {
14         int xt = x + dis[i][0];
15         int yt = y + dis[i][1];
16         if(xt >= 0 && yt >= 0 && xt < n && yt < m && map[xt][yt] == 'W') {
17             dfs(xt,yt);
18         }
19     }
20 }
21 int main(int argc, char const *argv[])
22 {
23     //freopen("input.txt","r",stdin);
24     while(scanf("%d %d",&n,&m) != EOF) {
25         for(int i = 0; i < n; i++) {
26             scanf("%s",map[i]);
27         }
28         int cnt = 0;
29         for(int i = 0; i < n; i++) {
30             for(int j = 0; j < m; j++) {
31                 if(map[i][j] == 'W') {
32                     dfs(i,j);
33                     cnt++;
34                 }
35             }
36         }
37         printf("%d
", cnt);
38     }
39     return 0;
40 }

采用深度优先搜索,搜索过的W改成.   ,直到没有W为止

搜索过几次就有几块

原文地址:https://www.cnblogs.com/jasonJie/p/5787968.html