Poj 2386 Lake Counting【Bfs】

来源:互联网 发布:订单制作软件 编辑:程序博客网 时间:2024/06/09 13:51

Lake Counting

Time Limit: 1000MS

 

Memory Limit: 65536K

Total Submissions: 28420

 

Accepted: 14246

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

Hint

OUTPUT DETAILS: 

There are three ponds: one in the upper left, one in the lower left,and one along the right side.

Source

USACO 2004 November

 

题目大意:找W的联通块,其连通要求为:W的八块附近的点可以有W。


思路:简单Bfs


AC代码:

#include<stdio.h>#include<string.h>#include<queue>using namespace std;struct zuobiao{    int x,y;}now,nex;int n,m;int vis[105][105];char a[105][105];int fx[8]={0,0,-1,1,1,-1,1,-1};int fy[8]={1,-1,0,0,1,-1,-1,1};void Bfs(int x,int y){    queue<zuobiao >s;    vis[x][y]=1;    now.x=x;    now.y=y;    s.push(now);    while(!s.empty())    {        now=s.front();        s.pop();        for(int i=0;i<8;i++)        {            nex.x=now.x+fx[i];            nex.y=now.y+fy[i];            if(nex.x>=0&&nex.x<n&&nex.y>=0&&nex.y<m&&vis[nex.x][nex.y]==0&&a[nex.x][nex.y]=='W')            {                vis[nex.x][nex.y]=1;                s.push(nex);            }        }    }}int main(){    while(~scanf("%d%d",&n,&m))    {        memset(vis,0,sizeof(vis));        for(int i=0;i<n;i++)        {            scanf("%s",a[i]);        }        int output=0;        for(int i=0;i<n;i++)        {            for(int j=0;j<m;j++)            {                if(vis[i][j]==0&&a[i][j]=='W')                {                                    output++;                    Bfs(i,j);                }            }        }        printf("%d\n",output);    }}





0 0