深入浅出学算法113-细胞
题目描述
一矩形阵列由数字0到9组成,数字1到9代表细胞,细胞的定义为沿细胞数字上下左右还是细胞数字
则为同一细胞,求给定矩形阵列的细胞个数。如:
阵列
4 10
0234500067
1034560500
2045600671
0000000089
有4个细胞。
输入
第一行输入2个整数n和m(均不大于60)
然后输入n行 每行m个数字(0到9之间,中间没有空格)
输出
输出一个整数,表示细胞数
样例输入
4 10
0234500067
1034560500
2045600671
0000000089
样例输出
4
题解:
搜索
源代码:
#include<bits/stdc++.h>
using namespace std;
int nx[]= {0,-1,0,1};
int ny[]= {-1,0,1,0};
char a[65][65];
int n,m;
void bfs(int x,int y) {
int cx,cy;
a[x][y]='0';
for(int i=0; i<4; i++) {
cx=nx[i]+x;
cy=ny[i]+y;
if(cx>=0&&cx<n&&cy>=0&&cy<m) if(a[cx][cy]!='0') bfs(cx,cy);
}
}
int main() {
int i,j,ans=0;
cin>>n>>m;
for(int i=0; i<n; i++) cin>>a[i];
for(int i=0; i<n; i++) {
for(int j=0; j<m; j++) {
if(a[i][j]!='0') {
ans++;
bfs(i,j);
}
}
}
cout<<ans<<endl;
return 0;
}