bfs解决的问题

1.连通性问题-----http://ybt.ssoier.cn:8088/problem_show.php?pid=1335

#include<iostream>
#include<queue>
using namespace std;
#define maxn 110
int a[maxn][maxn];
int cnt=0;
int turn[4][2]={{0,-1},{1,0},{0,1},{-1,0}};
struct s{
    int x,y;
}f,t;
int main()
{
    queue<s>q;
    int n,m;
    cin>>n>>m;
    for(int i=1;i<=n;i++)
        for(int j=1;j<=m;j++)
        cin>>a[i][j];
    for(int i=1;i<=n;i++)
        for(int j=1;j<=m;j++)
        {
            if(a[i][j]==1)
                {
                    a[i][j]=0;
                    ++cnt;
                    t.x=i,t.y=j;
                    q.push(t);//入队列
                    while(!q.empty())
                    {
                        f=q.front();
                        for(int k=0;k<4;k++)
                        {
                            int nx=f.x+turn[k][0];
                            int ny=f.y+turn[k][1];
                            if(a[nx][ny]==1)
                            {
                                a[nx][ny]=0;
                                t.x=nx,t.y=ny;
                                q.push(t);//入队列
                            }
                        }
                        q.pop();//出队列
                    }
                }
        }
    cout<<cnt<<endl;
}

 

posted @ 2019-06-17 12:41  saaas  阅读(262)  评论(0)    收藏  举报