bfs求连通块的个数

#include <iostream>
#include <stdio.h> 
#include <queue>
using namespace std;
struct node{
int x;
int y;
};
queue<node> Q;
const int maxn=200;
int map[maxn][maxn];
bool book[maxn][maxn]={false};
int m,n;
int next[4][2]={
0,-1,
0,1,
-1,0,
1,0
};
void bfs(int x1,int y1){
node nn;
nn.x=x1;   nn.y=y1;
while(!Q.empty()) Q.pop();  //再放第一个的时候,注意把队列清空; 
Q.push(nn);
book[x1][y1]=true;
while(Q.empty()==false){
node now=Q.front();
Q.pop();
for(int i=0;i<4;i++){
int nx=now.x+next[i][0];
int ny=now.y+next[i][1];
if(nx<0 || nx>m-1 || ny<0   || ny>n-1)  continue;
if(map[nx][ny]==0 || book[nx][ny]==true)  continue;        //
node final;
final.x=nx;
final.y=ny;
book[nx][ny]=true;
Q.push(final);
}
}
}
int main(int argc, char** argv) {
cin>>m>>n;
for(int i=0;i<m;i++){
for(int j=0;j<n;j++){
cin>>map[i][j];
}
}
int ans=0;

for(int i=0;i<m;i++){
for(int j=0;j<n;j++){
if(map[i][j]==1 && book[i][j]==false){
// node nn;
// nn.x=i; nn.y=j;
// Q.push(nn);
// book[i][j]=true;
bfs(i,j);
ans++;
}
}
}
cout<<ans<<endl;
return 0;

}



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值