细胞
用字符分离,再从头遍历,若不是0,则s+1,函数,并去其他方向看是否有不是0的数,若有,则变0,函数,若没有,退出函数,继续遍历
#include<bits/stdc++.h>
using namespace std;
char a[200][200];
int i,j;
int n,m,s=0;
int b[200][200];
void pd(int i,int j){
b[i][j]=0;
if(i+1<=n&&b[i+1][j]!=0){
pd(i+1,j);
}
if(j+1<=m&&b[i][j+1]!=0){
pd(i,j+1);
}
if(i-1>=1&&b[i-1][j]!=0){
pd(i-1,j);
}
if(j-1>=1&&b[i][j-1]!=0){
pd(i,j-1);
}
}
int main(){
cin>>n>>m;
for(i=1;i<=n;i++){
cin>>a[i];
}
for(i=1;i<=n;i++){
for(j=0;j<m;j++){
b[i][j+1]=int(a[i][j]-'0');
}
}
for(i=1;i<=n;i++){
for(j=1;j<=m;j++){
if(b[i][j]!=0){
b[i][j]=0;
s++;
if(i+1<=n&&b[i+1][j]!=0){
pd(i+1,j);
}
if(j+1<=m&&b[i][j+1]!=0){
pd(i,j+1);
}
if(i-1>=1&&b[i-1][j]!=0){
pd(i-1,j);
}
if(j-1>=1&&b[i][j-1]!=0){
pd(i,j-1);
}
}
}
}
cout<<s;
}
浙公网安备 33010602011771号