您的位置:首页 > 其它

POJ 2386 Lake Counting

2014-12-05 11:09 316 查看
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


題目大意:有個大小為N*M的庭院,下雨后形成了积水。八个方向有积水可视为链接在一起,求有多少处积水

输入如上图:w表示水 .表示陆地。

思路:如果遇到W就深度遍厉周围八个点,下面给出实现

#include<iostream>
#include <string.h>
using namespace std;

const int maxn = 100;
const int maxm = 100;
int n;
int m;
char f[maxn][maxm];
void dfs(int x,int y)
{
f[x][y] = '.';
for (int dx = -1;dx <= 1;dx ++)
{
for (int dy = -1; dy <= 1; dy ++)
{
int nx = x+dx;
int ny = y+dy;
if( 0 <= nx && 0 <= ny &&  nx < n && ny < m && f[nx][ny] == 'W')
dfs(nx, ny);
}
}

}

int main(int argc , const char * argv[])
{
cin>>n>>m;
int result = 0;

for (int i= 0; i<n; i++)
{
for (int j = 0; j<m; j++)
{
cin>>f[i][j];
}

}

for (int i= 0; i<n; i++)
{
for (int j = 0; j<m; j++)
{
if (f[i][j] == 'W')
{
dfs(i, j);
++result;
}
}

}
cout<<result;
return 0;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: