这道题是运用DFS求连通块的题目。
思路:首先,我们需要读懂题目,在这一步上,我们可能会误认为只有那种上下左右都是连通数字的,并且本身也是连通数字的才是连通块。其实不是,这里的意思就是说,如果说一个数字是大于0的,那么就是一个连通块了,只是如果说有和它相邻的,比如上下左右的都是连通数字的话,和它本事其实是同一个细胞,不能作为其他细胞,因此数目就不能计算进去。
那么我们就用dfs的功能深搜它的上下左右,用字符串0覆盖原先输入的字符,标记着我们已经遍历过了。那么接下来就好写了。
上代码:
#include<iostream>
#include<cstring>
#include<cstdlib>
#include<cmath>
#include<vector>
#include<algorithm>
#include<stack>
#include<queue>
#include<sstream>
#include<map>
#include<limits.h>
#include<set>
#define MAX 105
#define _for(i,a,b) for(int i=a;i<(b);i++)
#define ALL(x) x.begin(),x.end()
using namespace std;
typedef long long LL;
int n, m, counts;
char arr[MAX][MAX];
int zoux[4] = { -1,1,0,0 };
int zouy[4] = { 0,0,-1,1 };
void dfs(int x, int y) {
arr[x][y] = '0';
for (int i = 0; i < 4; i++) {
x+= zoux[i];
y+= zouy[i];
if (x >= 0 && x < n && y >= 0 && y < m && arr[x][y] != '0') {
dfs(x, y);
}
x -= zoux[i];
y -= zouy[i];
}
}
int main() {
ios::sync_with_stdio(false);
cin.tie(NULL); cout.tie(NULL);
cin >> n >> m;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++)
cin >> arr[i][j];
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (arr[i][j] != '0') {
dfs(i, j);
counts++;
}
}
}
cout << counts << endl;
return 0;
}