P1451 求细胞数量

题目链接

https://www.luogu.com.cn/problem/P1451

题目思路

只需要搜索在四个方向且不为0的数字块即可
dfs和bfs都可

题目代码

bfs

#include <iostream>
#include <algorithm>
#include <cstring>
#include <queue>

using namespace std;
typedef pair<int, int> PII;
const int N = 110;
int g[N][N];
bool st[N][N];
int n, m, ans;

void bfs(int x, int y)
{
    queue<PII> q;
    q.push({x, y});
    st[x][y] = true;
    while(q.size())
    {
        auto t = q.front();
        q.pop();
        int dx[4] = {-1, 0, 1, 0}, dy[4] = {0, 1, 0, -1};
        for(int i = 0; i < 4; i ++ )
        {
            int a = t.first + dx[i], b = t.second + dy[i];
            if(a >= 1 && a <= n && b >= 1 && b <= m && !st[a][b] && g[a][b] != 0)
            {
                st[a][b] = true;
                q.push({a, b});
            }
        }
    }
}

int main()
{
    cin >> n >> m;
    for(int i = 1; i <= n; i ++ )
        for(int j = 1; j <= m; j ++ )
        {
            char c;
            cin >> c;
            g[i][j] = c - '0';
        }
    int cnt = 0;
    for(int i = 1; i <= n; i ++ )
    {
        for(int j = 1; j <= m; j ++ )
        {
            if(g[i][j] && !st[i][j])
            {
                bfs(i, j);
                ans ++ ;
            }
        }
    }
    cout << ans << endl;
    return 0;
}

dfs

#include <iostream>
#include <algorithm>
#include <cstring>
#include <queue>

using namespace std;
typedef pair<int, int> PII;
const int N = 110;
int g[N][N];
bool st[N][N];
int n, m, ans;

void dfs(int x, int y)
{
    st[x][y] = true;
    int dx[4] = {-1, 0, 1, 0}, dy[4] = {0, 1, 0, -1};
    for(int i = 0; i < 4; i ++ )
    {
        int a = x + dx[i], b = y + dy[i];
        if(st[a][b] || g[a][b] == 0) continue;
        dfs(a, b);
    }
}

int main()
{
    cin >> n >> m;
    for(int i = 1; i <= n; i ++ )
        for(int j = 1; j <= m; j ++ )
        {
            char c;
            cin >> c;
            g[i][j] = c - '0';
        }
    int cnt = 0;
    for(int i = 1; i <= n; i ++ )
    {
        for(int j = 1; j <= m; j ++ )
        {
            if(g[i][j] != 0 && !st[i][j]) 
            {
                dfs(i, j);
                ans ++ ;
            }
        }
    }
    cout << ans << endl;
    return 0;
}
posted @   vacilie  阅读(28)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 张高兴的大模型开发实战:(一)使用 Selenium 进行网页爬虫
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
点击右上角即可分享
微信分享提示
主题色彩