1335:【例2-4】连通块
1 #include<iostream> 2 #include<cstdio> 3 #include<queue> 4 using namespace std; 5 const int N=105; 6 int n,m,ans,a[N][N],t[]={-1,1,0,0,0,0,-1,1}; 7 queue<int> q; 8 void cnt(){ 9 while(!q.empty()){ 10 int x=q.front(),y; 11 q.pop(); 12 y=q.front(); 13 q.pop(); 14 a[x][y]=0; 15 for(int i=0;i<4;i++){ 16 int nx=x+t[i],ny=y+t[i+4]; 17 if(nx>0&&nx<=n&&ny>0&&ny<=m&&a[nx][ny]){ 18 q.push(nx);q.push(ny); 19 } 20 } 21 } 22 ans++; 23 } 24 int main(){ 25 cin>>n>>m; 26 for(int i=1;i<=n;i++) 27 for(int j=1;j<=m;j++) 28 scanf("%d",&a[i][j]); 29 for(int i=1;i<=n;i++) 30 for(int j=1;j<=m;j++) 31 if(a[i][j]){ 32 q.push(i);q.push(j); 33 cnt(); 34 } 35 cout<<ans; 36 return 0; 37 }