洛谷 P1451:求细胞数量 ← Flood fill

​【题目来源】
https://www.luogu.com.cn/problem/P1451

【题目描述】
一矩形阵列由数字 0 到 9 组成,数字 1 到 9 代表细胞,细胞的定义为沿细胞数字上下左右若还是细胞数字则为同一细胞,求给定矩形阵列的细胞个数。

【输入格式】
第一行两个整数代表矩阵大小 n 和 m。
接下来 n 行,每行一个长度为 m 的只含字符 0 到 9 的字符串,代表这个 n×m 的矩阵。​​​​​​​

【输出格式】
一行一个整数代表细胞个数。​​​​​​​

【输入样例】
4 10
0234500067
1034560500
2045600671
0000000089​​​​​​​

【输出样例】
4

【数据范围】
对于100%的数据,保证 1≤n, m≤100。

【算法分析】
● 泛洪算法(Flood fill)是一种针对 “连通区域” 的处理思想。核心逻辑是:从一个起始点出发,像洪水扩散一样,遍历所有 “相邻且满足相同条件” 的结点(比如同颜色、同数值),并对这些结点进行标记、修改或计数。
● 典型场景:画图软件里的「油漆桶工具」—— 点击一个红色像素,所有和它连通的红色像素都会被换成蓝色,这个过程就是 Flood fill。

【算法代码一:dfs】

#include <bits/stdc++.h>
using namespace std;

const int N=1e2+5;
char mp[N][N];
int dx[]= {1,0,-1,0};
int dy[]= {0,1,0,-1};
int n,m,ans;

void dfs(int x,int y) {
    /*Mark the current position as '0'
    to indicate that it has been visited,
    in order to avoid redundant processing.*/
    mp[x][y]='0';
    for(int i=0; i<4; i++) {
        int tx=x+dx[i];
        int ty=y+dy[i];
        if(mp[tx][ty]>='1' && mp[tx][ty]<='9') {
            dfs(tx,ty);
        }
    }
}

int main() {
    cin>>n>>m;
    for(int i=0; i<n; i++) {
        for(int j=0; j<m; j++) {
            cin>>mp[i][j];
        }
    }

    for(int i=0; i<n; i++) {
        for(int j=0; j<m; j++) {
            if(mp[i][j]>='1' && mp[i][j]<='9') {
                dfs(i,j);
                ans++;
            }
        }
    }
    cout<<ans<<endl;

    return 0;
}

/*
in:
4 10
0234500067
1034560500
2045600671
0000000089

out:
4
*/

【算法代码二:bfs+pair】

#include<bits/stdc++.h>
using namespace std;

typedef pair<int,int> PII;
const int N=1e2+5;
char mp[N][N];
int dx[]= {1,0,-1,0};
int dy[]= {0,1,0,-1};
int n,m,ans;

void bfs(int x,int y) {
    queue<PII> q;
    q.push({x,y});
    mp[x][y]='0';
    while(!q.empty()) {
        PII t=q.front();
        q.pop();
        for(int i=0; i<4; i++) {
            int tx=t.first+dx[i];
            int ty=t.second+dy[i];
            if(tx>=0 && ty>=0 && tx<n && ty<m && mp[tx][ty]!='0') {
                mp[tx][ty]='0';
                q.push({tx,ty});
            }
        }
    }
}

int main() {
    cin>>n>>m;
    for(int i=0; i<n; i++) {
        for(int j=0; j<m; j++) {
            cin>>mp[i][j];
        }
    }

    for(int i=0; i<n; i++) {
        for(int j=0; j<m; j++) {
            if(mp[i][j]!='0') {
                bfs(i,j);
                ans++;
            }
        }
    }
    cout<<ans<<endl;

    return 0;
}

/*
in:
4 10
0234500067
1034560500
2045600671
0000000089

out:
4
*/





【参考文献】
https://blog.csdn.net/hnjzsyjyj/article/details/158656746
https://blog.csdn.net/hnjzsyjyj/article/details/158655296
https://blog.csdn.net/hnjzsyjyj/article/details/118642238
https://blog.csdn.net/hnjzsyjyj/article/details/158618461

 

 

posted @ 2026-03-04 17:05  Triwa  阅读(19)  评论(0)    收藏  举报