题目连接
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.
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.
…
解释:在一个W的附近八个点内有另外一个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’为 ‘.’