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

该程序实现了使用广度优先搜索(BFS)遍历一个包含0和1的矩阵,统计值为1的元素个数。通过队列进行节点的访问,并利用一个布尔型二维数组记录已访问的节点,避免重复计数。BFS遍历过程中,遇到值为1且未被访问过的节点,会进行BFS搜索并将答案累加。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在这里插入图片描述

#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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值