[算法]PAT-A_BFS模板

//给定一个m*n矩阵,与(x,y)点相邻的上下左右四个点为研究对象,若其中有包含(x,y)在内的连续的1,则构成一个块
//题目求解一个矩阵中块的个数
//该题在题库中有三维矩阵类似题目,都是BFS方法完成
//这里将本题作为BFS的模板题,运用queue实现
#include<queue>
#include<vector>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<iostream>
using namespace std;
const int maxn = 100;
int input[maxn][maxn];
int m, n;
int X_[4] = {0,0,1,-1};
int Y_[4] = {1,-1,0,0};
bool inq[maxn][maxn];
struct node{
    int x, y;
}Node;


bool judge(int x, int y){
    if(x>=m || x<0 || y>=n || y<0) return false;
    if(input[x][y]==0 || inq[x][y]==true) return false;
    return true;
}

void BFS(int x, int y){ //BFS的目的就是,对同一块的元素都标记上1,防止重复计数,仅此而已
    Node.x = x;
    Node.y = y;
    queue<node> q;
    q.push(Node);
    inq[x][y] = true;
    while(!q.empty()){
        node now = q.front();
        q.pop();
        for(int i=0;i<4;i++){
            int newx = now.x + X_[i];
            int newy = now.y + Y_[i];
            if(judge(newx, newy)){
                node A;
                A.x = newx;
                A.y = newy;
                q.push(A);
                inq[newx][newy] = true;
            }
        }
    }
}

int main(){
    scanf("%d%d", &m, &n);
    for(int i=0;i<m;i++){
        for(int j=0;j<n;j++){
            scanf("%d", &input[i][j]);
        }
    }
    int ans = 0;
    for(int x=0;x<m;x++){
        for(int y=0;y<n;y++){
            if(inq[x][y]==false && input[x][y]==1){
                ans++;
                BFS(x, y);
            }
        }
    }
    printf("%d\n", ans);
    return 0;
}

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值