求矩阵块的个数(BFS实现)

在这里插入图片描述

#include<cstdio>
#define maxn 16
#include<algorithm>
#include<vector>
#include<cmath>
#include<iostream>
#include<queue>
using namespace std;
//用队列实现BFS,队头结点出队并将相邻的点入队
//遍历整个矩阵,如果值为 1且没有被BFS遍历到过则执行BFS(row,column);
//BFS每执行完一次ans++
int m,n;
int maze[maxn][maxn];
bool hashtable[maxn][maxn]={
    
    false};
int X[]={
    
    0,-1,0,1};
int Y[]={
    
    -1,0,1,0};
struct node
{
    
    
    int r;
    int c;
};
bool judge(int row,int column)
{
    
    
    if(row<1||row>m||column<1||column>n){
    
    
        return false;
    }
    if(hashtable[row][column]==true||maze[row][column]==0){
    
    
        return false;
    }
    return true;
}
void BFS(int row,int column)
{
    
    
    queue<node> q1;
    node n;
    n.r=row;
    n.c=column;
    q1.push(n);
    while(!q1.empty()){
    
    
            n=q1.front();
        hashtable[n.r][n.c]=true;
        q1.pop();
        int x,y;
        for(int i=0;i<4;i++){
    
    
            x=n.r+X[i];
            y=n.c+Y[i];
            if(judge(x,y)){
    
    
                node t;
                t.r=x;
                t.c=y;
                q1.push(t);
            }
        }
    }
}
int main()
{
    
    
    scanf("%d %d",&m,&n);
    for(int i=1;i<=m;i++){
    
    
        for(int j=1;j<=n;j++){
    
    
            scanf("%d",&maze[i][j]);
        }
    }
    int ans=0;
    for(int i=1;i<=m;i++){
    
    
        for(int j=1;j<=n;j++){
    
    
            if(hashtable[i][j]==false&&maze[i][j]==1){
    
    
                BFS(i,j);
                ans++;
            }
        }
    }
    printf("%d\n",ans);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_45890608/article/details/111240688
今日推荐