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.
题目链接
http://poj.org/problem?id=2386
题目翻译
有一个大小为 N×M 的园子,雨后积起了水。八连通的积水被认为是连通在一起的(W表示积水,积水的上下左右和左上右上左下右下这八个方向如果有积水,则认为它们是连通的)。请求出园子里总共有多少水洼?
N,M<=100
题目分析
深度优先搜索即可。
遍历每一个点,如果值为W,则以这个点为起点开始深搜,答案 ans++。
在深搜的过程中,首先将当前点的值更改为.
,然后遍历当前点的八个方向上的点,如果值为W,则以其为起点进行深搜。
具体看代码吧。
AC代码
#include <iostream>
using namespace std;
int n, m;
char num[105][105];
void dfs(int x, int y)
{
num[x][y] = '.';
int d[] = {0, -1, 1}, i, j;
for (i = 0; i < 3; i++)
{
for (j = 0; j < 3; j++)
{
int x1 = x + d[i], y1 = y + d[j];
if (x1 < n && x1 >= 0 && y1 < m && y1 >= 0 && num[x1][y1] == 'W')
{
dfs(x1, y1);
}
}
}
}
int main()
{
int i, j, ans = 0;
cin >> n >> m;
for (i = 0; i < n; i++)
cin >> num[i];
for (i = 0; i < n; i++)
{
for (j = 0; j < m; j++)
{
if (num[i][j] == 'W')
{
dfs(i, j);
ans++;
}
}
}
cout << ans << endl;
return 0;
}