【题目描述】
一矩形阵列由数字0到9组成,数字1到9代表细胞,细胞的定义为沿细胞数字上下左右还是细胞数字则为同一细胞,求给定矩形阵列的细胞个数。
如:阵列
4 10
0234500067
1034560500
2045600671
0000000089
有4个细胞
输入
第一行为矩阵的行n和列m
下面为一个n×m的矩阵。
输出
细胞个数。
样例输入
4 10 0234500067 1034560500 2045600671 0000000089
样例输出
4
bfs板子题没什么好说的//_//
直接遍历整个数组 遇到非零数直接bfs将整个细胞染成0 计数器加一
(注意数组间元素没有空格 用字符串读入)
#include<bits/stdc++.h>
using namespace std;
int m,n,Ans,temp;
int dx[5]={0,0,0,1,-1};
int dy[5]={0,1,-1,0,0};
char mrx[1000][1000];
queue <int> xx;
queue <int> yy;
void BFS(int x,int y)
{
mrx[x][y]=0;
xx.push(x);
yy.push(y);
while(!xx.empty())
{
int tx=xx.front();
int ty=yy.front();
xx.pop();
yy.pop();
for(int i=1;i<=4;++i)
{
int xxx=tx+dx[i];
int yyy=ty+dy[i];
if(xxx>0&&yyy>0&&xxx<=m&&yyy<=n&&mrx[xxx][yyy]!='0')
{
xx.push(xxx);
yy.push(yyy);
mrx[xxx][yyy]='0';
}
}
}
}
int main()
{
cin>>m>>n;
for(int i=1;i<=m;i++)
{
scanf("%s",mrx[i]+1);
}
for(int i=1;i<=m;++i)
{
for(int j=1;j<=n;++j)
{
if(mrx[i][j]!='0')
{
BFS(i,j);
Ans++;
}
}
}
cout<<Ans;
return 0;
}
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/tech/pnotes/282130.html