BFS宽搜模板(求矩阵中连通块的个数)

给出一个n×m的矩阵,元素为0或1.称每个位置的上下左右与之相邻。如果矩阵中有若干个1是相邻的,那么这些1就构成了一个块。求矩阵中“块”的个数。 

#include
#include
#include
#include
#include 
#include 
using namespace std;
typedef long long ll;

const int maxn=100;
int Map[100][100];
int m,n,ans;
int vis[maxn][maxn];//标记已走过的

struct node
{
    int a,b;
}Node;

bool judge(int a,int b)
{
    if(a>=n||b>=m||b<0||a<0)
        return false;
    if(vis[a][b]==1||Map[a][b]==0)
        return false;
    return true;
}

int Z[4]={0,0,1,-1};
int P[4]={1,-1,0,0};
void BFS(int x,int y)
{
    queue q;
    Node.a=x;
    Node.b=y;
    q.push(Node);
    vis[x][y]=1;
    while(!q.empty())
    {
        node top=q.front();
        q.pop();
        for(int i=0;i<4;i++)
        {
            int xx=Z[i]+top.a;
            int yy=P[i]+top.b;
            if(judge(xx,yy))
            {
                Node.a=xx;
                Node.b=yy;
                q.push(Node);//当前结点的子项入队
                vis[xx][yy]=1;
            }
        }
    }
}

int main()
{
    while(scanf("%d%d",&n,&m)!=EOF)//矩阵的长和宽
    {
        ans=0;
        memset(vis,0,sizeof(vis));
        for(int i=0;i>Map[i][j];
             }

           }
           //cout<

 

你可能感兴趣的:(DFS&BFS)