Const_Lin
你从远方来, 我到远方去, 遥远的路程经过这里, 天空一无所有, 为何给我安慰。

题目描述:

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 char map[100][100];
 3 int n,m;
 4 void dfs(int i,int j);
 5 int main()
 6 {
 7     using namespace std;
 8     //int n,m;
 9     int sum = 0;
10     cin >> n >> m;
11     //char map[n][m];
12     for(int i = 0;i < n;i++)
13         for(int j = 0;j < m;j++)
14             cin >> map[i][j];
15     for(int i = 0;i < n;i++)
16         for(int j = 0;j < m;j++)
17         {
18             if(map[i][j] == 'W')
19             {
20                 dfs(i,j);
21                 sum++;
22             }
23         }
24     cout << sum << endl;
25     return 0;
26 }
27 
28 void dfs(int i,int j)
29 {
30     int x,y;
31     map[i][j] = '.';
32     for(int nx = -1;nx <= 1;nx++)
33         for(int ny = -1;ny <= 1;ny++)
34         {
35             x = i + nx;
36             y = j + ny;
37             if(x <= n && y <= m && x >= 0 && y >= 0 && map[x][y] == 'W')
38                 dfs(x,y);
39         }
40 }

代码分析:

这道题用到了深度优先搜索法,对这个算法也是最近刚接触,所以可能说的不太好,所以恳请读者指正。

深度优先搜索法,通俗地讲,就是从初始状态,在一个方向上,一直访问到最后一个状态,然后再返回到前一个个状态,换个一个方向,继续访问到最后一个状态。

在这道题目上,我们从任意一个的'W'可以访问,看它的周围的八个状态,哪个状态是'W',就从这个状态再继续深入,直到某个状态周围的八个状态都不是'W',则返回前一个状态,直到这个方向上都不是'W',则这个方向的状态都访问完。在这里我们将'W'改为'.',表示访问过。

1次dfs后与初始的这个W连接的所以W就都被替换为'.',直到图中不再存在W为止,总共进行dfs的次数就是答案。

参考书籍:[挑战程序设计竞赛]

posted on 2013-11-18 21:32  Const_Lin  阅读(208)  评论(0)    收藏  举报