luogu1451 求细胞数量
时空限制 1000ms/128MB
题目描述
一矩形阵列由数字0到9组成,数字1到9代表细胞,细胞的定义为沿细胞数字上下左右若还是细胞数字则为同一细胞,求给定矩形阵列的细胞个数。(1<=m,n<=100)?
输入输出格式
输入格式:
输入:整数m,n(m行,n列)
矩阵
输出格式:
输出:细胞的个数
输入输出样例
输入样例#1:
4 10 0234500067 1034560500 2045600671 0000000089
输出样例#1:
4
代码
法一:STL队列
#include<iostream>
#include<string>
#include<queue>
using namespace std;
const int N = 105;
const int dx[] = {-1, 0, 1, 0},
dy[] = { 0, 1, 0,-1};
int n,m,ans=0;
bool g[N][N]; //存图,并起标记作用
struct node{
int x,y;
node(){ }
node(int a,int b):x(a),y(b){ }
};
queue<node> q;
void bfs(int x,int y){
ans++; //每次搜索,一定可以搜出一个细胞
q.push(node(x,y)); //把该坐标入队
g[x][y] = false; //入队后变为非细胞
while (!q.empty()){ //队列非空
node k=q.front(); q.pop(); //取队头,队头出队
for (int i=0; i<4; i++){
int xx=k.x+dx[i],yy=k.y+dy[i];
if (xx>=0 && xx<n && yy>=0 && yy<m && g[xx][yy]){
q.push(node(xx,yy));//把(xx,yy)入队
g[xx][yy] = false; //入队后变为非细胞
}
}
}
}
int main(){
cin>>n>>m;
string s;
for (int i=0; i<n; i++){
cin>>s;
for (int j=0; j<m; j++)
if (s[j]!='0') g[i][j]=true; //ture是细胞 false不是细胞
}
for (int i=0; i<n; i++)
for (int j=0; j<m; j++)
if (g[i][j]) bfs(i,j); //枚举没访问细胞位置
cout<<ans<<endl;
return 0;
}
法二:手动队列
#include<iostream>
#include<string>
using namespace std;
const int N = 105;
const int dx[] = {-1, 0, 1, 0},
dy[] = { 0, 1, 0,-1};
int n,m,que[N*N][2],head,tail,ans=0;
bool g[N][N]; //存图,并起访问标记作用
void bfs(int x,int y){
ans++; //每次搜索,一定可以搜出一个细胞
que[++tail][0]=x; que[tail][1]=y; //把该坐标入队
g[x][y] = false; //入队后变为非细胞
while (head<tail){ //队列非空
head++; //取队头,队头出队
for (int i=0; i<4; i++){
int xx=que[head][0]+dx[i],yy=que[head][1]+dy[i];
if (xx>=0 && xx<n && yy>=0 && yy<m && g[xx][yy]){
que[++tail][0]=xx; que[tail][1]=yy; //把(xx,yy)入队
g[xx][yy] = false; //访入队后变为非细胞
}
}
}
}
int main(){
cin>>n>>m;
string s;
for (int i=0; i<n; i++){
cin>>s;
for (int j=0; j<m; j++)
if (s[j]!='0') g[i][j]=true; //ture是细胞 false不是细胞
}
for (int i=0; i<n; i++)
for (int j=0; j<m; j++)
if (g[i][j]) bfs(i,j); //枚举没访问细胞位置
cout<<ans<<endl;
return 0;
}