bfs求连通块的个数

#include
#include  
#include
using namespace std;
struct node{
int x;
int y;
};
queue 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 for(int j=0;j cin>>map[i][j];
}
}
int ans=0;

for(int i=0;i for(int j=0;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< return 0;

}



你可能感兴趣的:(bfs)