poj 2386:Lake Counting(简单DFS深搜)

Lake Counting
Time Limit: 1000MS   Memory Limit: 65536K
Total Submissions: 18201   Accepted: 9192

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.

Source


 
  简单深搜
  遍历迷宫中所有的点,如果是‘W’,开始dfs搜索,将它临近的八个方向是‘W’的点全部走遍,并将走过的点变为‘.’,这样这一块‘W’区域就全部走完。一共走过了多少个这样的区域,就是结果。
  代码:
 1 #include <iostream>
 2 
 3 using namespace std;
 4 int n,m;
 5 char a[105][105];
 6 int dx[8] = {0,1,1,1,0,-1,-1,-1};   //八个方向
 7 int dy[8] = {1,1,0,-1,-1,-1,0,1};
 8 bool judge(int x,int y)    
 9 {
10     if(x<1 || x>n || y<1 || y>m)
11         return 1;
12     if(a[x][y]!='W')
13         return 1;
14     return 0;
15 }
16 void dfs(int x,int y)
17 {
18     a[x][y] = '.';  //将‘W’转化为‘.’
19     for(int i=0;i<8;i++){
20         int nx = x + dx[i];
21         int ny = y + dy[i];
22         //如果这一步是‘W’,且没有越界,可以走。
23         if(judge(nx,ny))
24             continue;
25         dfs(nx,ny);
26     }
27 }
28 int main()
29 {
30     while(cin>>n>>m){
31         int sum = 0;
32         for(int i=1;i<=n;i++)
33             for(int j=1;j<=m;j++)
34                 cin>>a[i][j];
35         for(int i=1;i<=n;i++)
36             for(int j=1;j<=m;j++)
37                 if(a[i][j]=='W'){
38                     sum++;
39                     dfs(i,j);
40                 }
41         cout<<sum<<endl;
42     }
43     return 0;
44 }
45     

 

Freecode : www.cnblogs.com/yym2013

posted @ 2014-03-24 15:08  Freecode#  阅读(271)  评论(0编辑  收藏  举报