题目描述:
一矩形阵列由数字0到9组成,数字1到9代表细胞,细胞的定义为沿细胞数字上下左右还是细胞数字则为同一细胞,求给定矩形阵列的细胞个数。如:
阵列
4 10
0234500067
1034560500
2045600671
0000000089
输出:
4
【代码】
1 #include<iostream> 2 #include<cstdio> 3 #include<cstdlib> 4 #include<cstring> 5 using namespace std; 6 bool ccell[100][100];//是否有细胞 7 char s[100]; 8 int sum=0; 9 int dx[4]={-1,0,1,0},//上下左右查找 10 dy[4]={0,1,0,-1}; 11 void bfs(int,int);//广搜 12 int qque[100][3];//队列 13 char qq[3]; //存换行 14 int n,m; 15 int main() 16 { 17 18 scanf("%d%d",&n,&m); 19 memset(ccell,1,sizeof(ccell)); 20 gets(qq);//存个换行符orz 21 for(int i=0;i<=n-1;i++) 22 { 23 gets(s); 24 for(int j=0;j<=m-1;j++) 25 { 26 if(s[j]=='0')ccell[i][j]=0;//没有细胞时标记0; 27 } 28 } 29 for(int i=0;i<=n-1;i++) 30 { 31 for(int j=0;j<=m-1;j++) 32 if(ccell[i][j])//如果这里有细胞就广搜 33 bfs(i,j); 34 } 35 printf("%d",sum); 36 return 0; 37 } 38 void bfs(int i,int j) 39 { 40 int head=0,tail=1; 41 sum++; 42 do 43 { 44 head++; 45 qque[1][1]=i;qque[1][2]=j; 46 for(int i=0;i<=3;i++) 47 { 48 int x=qque[head][1]+dx[i],y=qque[head][2]+dy[i];//看看其上下左右有没有 49 if(x>=0&&x<n&&y>=0&&y<m&&ccell[x][y])//没超过边界并且有细胞 50 { 51 ccell[x][y]=0;//打标记 52 tail++;//入队 53 qque[tail][1]=x; 54 qque[tail][2]=y; 55 } 56 } 57 }while(head<tail); 58 }