洛谷 1451.求细胞数量

这道题是运用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;
}

  • 7
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值