POJ 2386 LakeCounting
原题
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
题意
因为下雨农场里有许多积水,连接在一起的积水为一个池塘,问一共有几片池塘。
’W’为有积水的土地,’.'为干燥的土地,这是一道基础的dfs题。
输入:第一行是农场的宽N和长M。(1 <= N, M <= 100)
接下来N+1行为每一行的土地情况,每行有M个字符分别为’W’,’.’。
输出:池塘的个数。
直接上代码
#include<iostream>
using namespace std;
char field[101][101];
int n, m, sum = 0;
void dfs(int x, int y)
{
field[x][y] = '.'; //每找到一个'W'就把它标记为'.'
for(int i = x - 1; i <= x + 1; i++)//该点周围一圈是否有积水
for(int j = y - 1; j <= y + 1; j++)
if(x >= 0 && x < n && y >= 0 && y < m && field[i][j] == 'W')
dfs(i,j);
}
int main()
{
cin >> n >> m;
for(int i = 0; i < n; i++)
for(int j = 0; j < m; j++)
cin >> field[i][j];
for(int i = 0; i < n; i++)
for(int j = 0; j < m; j++)
if(field[i][j] == 'W'){
dfs(i,j);sum++;//每找到一个'W'都会把它自己以及与它相连的所有'W'都标记为'.'
} //所以直接用sum记录即可
cout << sum << endl;
return 0;
}