## 题目连接

http://poj.org/problem?id=2386

## 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.

10 12
W……..WW.
.WWW…..WWW
….WW…WW.
………WW.
………W..
..W……W..
.W.W…..WW.
W.W.W…..W.
.W.W……W.
..W…….W.

3

.W.

## 代码

#include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
#include<cmath>
#include<string>
#include<cctype>
#include<algorithm>
#include<vector>
#define INF  1e9+7
using namespace std;
int n,m;
char a[110][110];
void dfs(int q,int p){
a[q][p]='.';
for (int i = -1; i <=1 ; ++i)
{
for (int j = -1; j <=1 ; ++j)
{
if (a[q+i][p+j]=='W'&&q+i>=0&&q+i<n&&p+j>=0&&p+j<m)
{
a[q+i][p+j]='.';
dfs(q+i,p+j);
}
}
}
}
int main(int argc, char const *argv[])
{
scanf("%d%d",&n,&m);
memset(a,0,sizeof(a));
//  fflush(stdin);   //清空输入流  上一个scanf预留的\n
for (int i = 0; i < n; ++i)
{
for (int j = 0; j < m; ++j)
{
cin>>a[i][j];
// scanf("%c",&a[i][j]);
}
}
int ans=0;
for (int i = 0; i < n; ++i)
{
for (int j = 0; j < m; ++j)
{
if (a[i][j]=='W')
{
dfs(i,j);
ans++;
}
}
}
printf("%d\n",ans );
return 0;
}

## Get

• 从-1到1 对一个点相接的八个点扫描，需要保证-1的之后的点仍然是在数组范围值内的
• 两个scanf连用的时候，用fflush(stdin)清空输入流，避免下一个scanf读入\n
• 记得修改 ‘W’为 ‘.’

#### POJ NO.2386 Lake Counting(算水洼)

2016-01-19 17:24:39

#### 水洼 POJ2386 挑战程序设计竞赛

2016-09-22 20:32:49

#### 编程算法 - 水洼的数量 代码(C)

2014-07-17 14:21:10

#### poj2386水洼dfs

2015-08-06 21:17:17

#### 广度优先搜索和深度优先搜索—N皇后问题

2016-03-14 20:40:36

#### 用深度优先搜索（DFS）（回溯法）解决N皇后问题（Leetcode 51）

2016-04-10 21:03:02

#### 迷宫寻址中深度优先搜索的递归和非递归算法比较

2014-11-12 15:52:20

#### 用JAVA实现深度优先搜索

2015-01-13 17:14:37

#### 生成图-深度优先搜索/宽度优先搜索

2014-12-03 17:54:03

#### 北大ACM1010-深度优先搜索（DFS）初探

2015-04-23 21:47:19

## 不良信息举报

POJ2386水洼问题 优先深度搜索