poj 2386 Lake Counting(搜索,种子填充法)


最简单的bfs搜索,要理解bfs是对所有可能进行遍历,
利用的是搜索的扩散,或者说是种子填充法

#include<cstdio>

#include<cstring>

#include<queue>

using namespace std;

int n,m;

const int Maxsize = 105;

int maze[Maxsize][Maxsize];

int dir[8][2]={{1,1},{1,-1},{-1,1},{-1,-1},{1,0},{-1,0},{0,-1},{0,1}};

typedef struct
{
    int x,y;
}node;

int main()
{
    void bfs(node start);
    char ch;
    int cnt;
    node start;
    while(scanf("%d %d",&n,&m)!=EOF)
    {
        cnt = 0;
        memset(maze,0,sizeof(maze));
        for(int i = 0 ; i < n ; i ++)
        {
            getchar();
            for(int j = 0 ; j < m ; j++)
            {
                scanf("%c",&ch);
                if(ch == '.')           //记录矩阵的信息。
                {
                    maze[i][j] = 1;
                }
            }
        }
        for(int i = 0 ; i < n ; i++)
        {
            for(int j = 0 ; j < m ; j++)
            {
                if(!maze[i][j])
                {
                    start.x = i;start.y = j; //每出现一次可以搜索的点,用bfs对其八个方向进行全搜索
                    maze[i][j] = 1;//对矩阵的信息进行修改,一次可使“一块”搜索修改完毕
                    bfs(start);
                    cnt++; 
                }
            }
        }
        printf("%d\n",cnt);
    }
    return 0;
}
void bfs(node start)
{
    node pre,cur;
    pre = start;
    queue<node>q;
    q.push(pre);
    while(!q.empty())
    {
        pre = q.front();
        q.pop();
        for(int i = 0 ; i < 8 ; i++)
        {
            cur.x = pre.x + dir[i][0];
            cur.y = pre.y + dir[i][1];
            if(maze[cur.x][cur.y])continue;
            if(cur.x < 0 || cur.x >=n || cur.y < 0 || cur.y >= m)continue;
            maze[cur.x][cur.y] = 1;
            q.push(cur);
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值