POJ 2386 Lake Counting(BFS)

来源:互联网 发布:谷歌全球域名 编辑:程序博客网 时间:2024/06/09 14:30

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,如果上下左右都是W,那么我们算作一个大W,除此之外左上角、右上角、左下角、右下角,也能够构成一块。 所以我们要判断一块土地中有多少大水池(W),因此这里有八个方向, 我们在搜索的时候要沿着8个方向进行。 好了,现在我们知道了题意那么我们怎么来写出这道题呢?

步骤: 首先我们找到第一个出现的W 也就是一块水池的位置,看的周围是否还有W,如果有我们就将周围的水池全部变成空地,当然这里有一个问题,如果水池1的旁边是水池2,但水池2的旁边还有水池3,水池3的旁边还有水池4.。。。。 这样怎么办呢?

所以我们就用到了搜索的一个技巧,将满足条件的压入队列中,下次再以他作为一个基准值,开始搜索。也就是首先以水池1为基准值,开始找他周围的水池,假如找到了水池2,那么我们将水池2填满,但是要将水池2记录下来,下次从水池2开始判断周围有没有其他的水池。 以此类推。。 直到将所有能够与水池1合成一个大水池的水池填满。

好了,现在让我们开始上代码吧。 (已经AC了)

#include<iostream>#include<stdio.h>using namespace std;#include<queue>char map[105][105];int dir[8][2]={{0,1},{0,-1},{-1,0},{1,0},{-1,-1},{-1,1},{1,-1},{1,1}};      //8个方向struct node{    int x,y;};int m,n;void bfs(int x,int y){    int i;    queue <struct node> s;    struct node ne,c;    c.x=x; c.y=y;    s.push(c);//将第一个基准值压入队列中,并且变为空地    map[x][y]='.';    while(!s.empty())//所有的水池被填满了,并且周围也没有水池了    {        c=s.front();//提取每次保存的基准值        s.pop();// 提取完后,取出队列,以减少空间        for(i=0;i<8;i++)//沿8个方向开始搜索        {            ne.x=c.x+dir[i][0];            ne.y=c.y+dir[i][1];            if(map[ne.x][ne.y]=='W'&&ne.x>=0&&ne.y>=0&&ne.x<m&&ne.y<n)//为水池,并且没有超过空地的范围,就压入队列,作为下一次的基准值            {                s.push(ne);                map[ne.x][ne.y]='.';            }        }    }}int main(){    while(cin>>m>>n)    {        getchar();        int i,j;        int counti=0;        for(i=0;i<m;i++)        {            gets(map[i]);        }        for(i=0;i<m;i++)        {            for(j=0;j<n;j++)            {                   if(map[i][j]=='W')//找到每一个大水池中第一次出现的小水池,以它作为基准值。                {                    counti++;//每填满一个大水池,就计数                    bfs(i,j);                }            }        }        cout<<counti<<endl;    }}
0 0