码迷,mamicode.com
首页 > 其他好文 > 详细

1329:【例8.2】细胞

时间:2019-04-14 17:50:01      阅读:147      评论:0      收藏:0      [点我收藏+]

标签:class   front   void   next   include   ext   mes   href   code   

【题目描述】

一矩形阵列由数字00到99组成,数字11到99代表细胞,细胞的定义为沿细胞数字上下左右还是细胞数字则为同一细胞,求给定矩形阵列的细胞个数。如:

阵列

 

4 10
0234500067
1034560500
2045600671
0000000089

 

44个细胞。

【输入】

第一行为矩阵的行nn和列mm;

下面为一个n×mn×m的矩阵。

【输出】

细胞个数。

【输入样例】

4 10
0234500067
1034560500
2045600671
0000000089

【输出样例】

4

【来源】

一本通:http://ybt.ssoier.cn:8088/problem_show.php?pid=1329

洛谷:https://www.luogu.org/problemnew/show/P1451

 

       这是我的第一篇博客。这道题是一道比较简单的搜索题,但我不知道什么才叫细胞。还有就是,为什么输入不能从0开始??

      注意一下这题用int定义数组不行,要用字符串.

DFS:

 1 #include<iostream>
 2 #include<cstdio>
 3 using namespace std;
 4 int next[4][2]={{1,0},{-1,0},{0,-1},{0,1}};
 5 int n,m,ans;
 6 char a[500][500];
 7 int i,j;
 8 int dfs(int x,int y)
 9 {
10     int nx,ny,k;
11     for(k=0;k<=3;k++)
12     {
13         nx=x+next[k][0];
14         ny=y+next[k][1];
15         if(nx>=0&&nx<n&&ny>=0&&ny<m&&a[nx][ny]!=0)
16         {
17             a[nx][ny]=0;
18             dfs(nx,ny);
19         }
20     }
21 }
22 int main()
23 {
24     scanf("%d%d",&n,&m);
25     for(i=0;i<n;i++)
26     scanf("%s",a[i]);
27     for(i=0;i<n;i++)
28     for(j=0;j<m;j++)
29     if(a[i][j]!=0)
30     {
31         ans++;
32         dfs(i,j);
33     }
34     printf("%d",ans);
35     return 0;
36 } 

BFS:

 1 #include<bits/stdc++.h>
 2 using namespace std;
 3 struct node
 4 {
 5     int x,y;
 6 };
 7 int n,m;
 8 int u[4][2]={{1,0},{-1,0},{0,1},{0,-1}};
 9 char s[300][300];
10  
11 void BFS(int a,int b)
12 {
13     queue<node>Q;
14     s[a][b]=0;
15     node c;
16     c.x=a;
17     c.y=b;
18     Q.push(c);
19     while(!Q.empty()){
20         node d=Q.front();
21         for(int i=0;i<4;i++){
22             int xx=d.x+u[i][0];
23             int yy=d.y+u[i][1];
24             if(xx>=0&&xx<n&&yy>=0&&yy<m&&(s[xx][yy]!=0)){
25                 s[xx][yy]=0;
26                 node e;
27                 e.x=xx;
28                 e.y=yy;
29                 Q.push(e);
30             }
31         }
32         Q.pop();
33     }
34 }
35 int main()
36 {
37     cin>>n>>m;
38     for(int i=0;i<n;i++)
39         for(int j=0;j<m;j++)
40         cin>>s[i][j];
41     int sum=0;
42     for(int i=0;i<n;i++){
43         for(int j=0;j<m;j++){
44             if(s[i][j]!=0){
45                 sum++;
46                 BFS(i,j);
47             }
48         }
49     }
50     cout<<sum<<endl;
51     return 0;}

 

1329:【例8.2】细胞

标签:class   front   void   next   include   ext   mes   href   code   

原文地址:https://www.cnblogs.com/fuxiqi/p/10705952.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!