细胞搜索(广搜)

题目描述
一矩形阵列由数字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 }

 

转载于:https://www.cnblogs.com/zzyh/p/6650266.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值