poj 2386 Lake Counting
Lake Counting
Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 25183 | Accepted: 12688 |
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.
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.
* 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
一道典型的dfs,思路并不难,,可是在计算一个点周围的八个点的时候,,我是单独一个一个写出来的,,
后来看了挑战程序设计,才知道大牛用的两层循环解决,,而且是是把遍历后的'W'改成'.'而不是像我一样另外设置一个flag数组(既麻烦又容易错),大牛,,这种小地方在比赛中时往往可以拉开差距
#include <iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
char map[101][101];
int num,n,m;
bool bian(int x,int y)
{
map[x][y]='.';
for(int i=-1;i<=1;i++)
for(int j=-1;j<=1;j++)
if(map[x+i][y+j]=='W')
bian(x+i,y+j);
return 0;
}
int main()
{
while(cin>>n>>m)
{
num=0;
memset(map,0,sizeof(map));
for(int i=1;i<=n;i++)
for(int j=1;j<=m;j++)
cin>>map[i][j];
for(int i=1;i<=n;i++)
for(int j=1;j<=m;j++)
if(map[i][j]=='W')
{
bian(i,j);
num++;
}
cout<<num<<endl;
}
return 0;
}
你说,我们都会幸福的,对吧?