求细胞数量 - 洛谷
/*
* @Description: To iterate is human, to recurse divine.
* @Autor: Recursion
* @Date: 2022-04-05 20:25:15
* @LastEditTime: 2022-04-05 20:31:43
*/
#include <bits/stdc++.h>
#define LL long long
using namespace std;
const int maxn = 1e6 + 10;
const int mod = 1e9 + 7;
const int INF = 1e9 + 10;
const int N = 1e4;
char a[N][N];
int n,m,ans;
int dx[4] = {0,1,-1,0};
int dy[4] = {1,0,0,-1};
void dfs(int x,int y)
{
a[x][y] = '0';
for(int i = 0;i < 4;i ++)
for(int j = 0;j < 4;j ++){
int tx = x + dx[i];
int ty = y + dy[i];
if(tx>0&&tx<=n&&ty>0&&ty<=m&&a[tx][ty]!='0')
dfs(tx,ty);
}
}
int main()
{
ios::sync_with_stdio(false);
cin >> n >> m;
for(int i = 1;i <= n;i ++)
for(int j = 1;j <= m;j ++)
cin >> a[i][j];
for(int i = 1;i <= n;i ++)
for(int j = 1;j <= m;j ++){
if(a[i][j] != '0'){
dfs(i,j);
ans++;
}
}
cout << ans << endl;
// cout << a[i][j];
return 0;
}
|