Lake Counting
Time Limit: 1000MS
Memory Limit: 65536K
Total Submissions: 54817
Accepted: 26764
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
思想:将图的遍历问题转化为树的遍历问题
做法:
1)采用深度优先搜索来做这道题,将每个’W’作为树的根节点,来进行深度优先搜索(dfs),并将已经访问过的结点’W’标记为’.’,这样不会造成重复访问同一个结点
2)我们用for循环遍历每个还没有被访问’W’的结点并实施dfs,那么我们用了几次dfs,就有几块Lake。
ps:深度优先遍历从某个顶点出发,首先访问这个顶点,然后找出刚访问这个结点的第一个未被访问的邻结点,然后再以此邻结点为顶点,继续找它的下一个新的顶点进行访问,重复此步骤,直到所有结点都被访问完为止。
以下为ac的代码:
#include<iostream>
#include<iomanip>
int N, M;
char field[100][101];
using namespace std;
void dfs(int x, int y) {
field[x][y] = '.'; //将访问过的'W'标记为'.',以判断已经访问过了
//搜索8个方向
for (int dx = -1; dx <= 1; dx++) {
for (int dy = -1; dy <= 1; dy++) {
int nx = x + dx;
int ny = y + dy;
//判断是否可以移动及是否已经访问过,若field[nx][ny] == 'W',则未访问过。
if (0 <= nx && nx < N && 0 <= ny && ny < M&&field[nx][ny] == 'W')
dfs(nx, ny); //向8个方向移动之后,将新的点作为根节点进行遍历(递归完成dfs的操作)。
}
}
}
void solve() {
int res = 0;
for (int i = 0; i < N; i++) {
for (int j = 0; j < M; j++) {
//遍历每一个还未被标记为'.'的'W',并用dfs;
if (field[i][j] == 'W') {
dfs(i, j);
res++; //lake的数量
}
}
}
cout << res;
}
int main()
{
cin >> N >> M;
for (int i = 0; i < N; i++) {
for (int j = 0; j < M; j++) {
cin >> field[i][j];
}
}
solve();
}