洛谷 P1451【细胞】

题目描述

一矩形阵列由数字0到9组成,数字1到9代表细胞,细胞的定义为沿细胞数字上下左右若还是细胞数字则为同一细胞,求给定矩形阵列的细胞个数。(1<=m,n<=100)?

输入输出格式

输入格式1

输入:整数m,n(m行,n列)

矩阵

输出格式1

输出:细胞的个数

输入输出样例

输入样例1

4  10
0234500067
1034560500
2045600671
0000000089

输出样例1

4

解题思路

  首先,一定要字符读入,然后遍历,遇到不是0就搜索它,把它连着的全变成0,ans++,最后输出即可。

题解

 1 #include<bits/stdc++.h>
 2 using namespace std;
 3 int n,m,ans; 
 4 char mp[101][101];
 5 int dir[4][2]={0,1,0,-1,1,0,-1,0};//四个方向 
 6 struct node{
 7     int X;
 8     int Y;//坐标 
 9     node(){}
10     node(int xx,int yy)//构造函数 
11     {
12         X=xx;
13         Y=yy;
14      } 
15 };
16 queue<node> q;//队列 
17 void dfs(int x,int y)
18 {
19     q.push(node(x,y));
20     mp[x][y]='0';//打标记 
21     while(!q.empty())
22     {
23         node head=q.front();//取出队头 
24         q.pop();
25         for(int i=0;i<4;i++)//四方向拓展 
26         {
27             int tx=head.X+dir[i][0];
28             int ty=head.Y+dir[i][1];
29             if(mp[tx][ty]!='0'&&tx>=1&&tx<=n&&ty>=1&&ty<=m)//是同伙并且在范围内就干掉他 
30             {
31                 mp[tx][ty]='0';//干掉 
32                 q.push(node(tx,ty));//继续干 
33             }
34         }
35     }
36 }
37 int main()
38 {
39     cin>>n>>m;
40     for(int i=1;i<=n;i++)
41     {
42         for(int j=1;j<=m;j++)
43         {
44             cin>>mp[i][j];//存图 
45         }
46     }
47     for(int i=1;i<=n;i++)
48     {
49         for(int j=1;j<=m;j++)
50         {
51             if(mp[i][j]!='0')//遍历到不是0,就把它变成0,ans++ 
52             {
53                 ans++;
54                 dfs(i,j);
55             }
56         }
57     }
58     cout<<ans;//输出细胞 
59     return 0;
60 }
原文地址:https://www.cnblogs.com/hualian/p/11185628.html