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.
OutputLine 1: The number of ponds in Farmer John's field.
这是POJ-2386题目,以下是我的代码,我不明白为什么在我输入
4 4
.WW.
WW.W
.(这一排是4个.号)
W.W.
的时候,它会输出 4 而不是正确答案 3。
#include<iostream>
#include<cstring>
#include<algorithm>
#include<queue>
using namespace std;
const int maxn = 105;
struct node{
int x,y;
}Node;
int n,m;
char farm[maxn][maxn];
int dx[8]={1,1,0,-1,-1,-1,0,1};
int dy[8]={0,1,1,1,0,-1,-1,-1};
bool vis[maxn][maxn] = {false};
int ans=0;
//判断当前这个点(x,y)是否合格
bool judge(int x,int y){
if(x>=n||x<0||y>=m||y<0) return false;
if(vis[x][y]) return false;
if(farm[x][y]=='.') return false;
return true;
}
//广搜:八个方向都搜一遍,满足相邻条件就标记为访问过
void bfs(int x, int y){
queue<node> q;
Node.x = x, Node.y = y;
q.push(Node);
vis[x][y] = true;
while(!q.empty()){
node top = q.front();
q.pop();
for(int i = 0; i < 8; i++){
int xx = top.x + dx[i];
int yy = top.y + dy[i];
if(judge(xx, yy)){
Node.x = xx, Node.y = yy;
q.push(Node);
vis[xx][yy] = true;
}
}
}
}
int main(){
cin>>n>>m;
for(int x=0;x < n; x++){
for(int y=0;y<m; y++){
cin>>farm[x][y];
}
}
//遍历整个farm,如果存在没有访问过的点W,就开始广搜,直至辐射范围结束。
for(int x=0;x < n; x++){
for(int y=0;y<m; y++){
if(farm[x][y]=='W'&&!vis[x][y]){
bfs(x,y);
ans++;
}
}
}
cout<<ans<<endl;
return 0;
}