[FloodFill] aw1097. 池塘计数(bfs+dfs+FloodFill+模板题)

本文介绍了如何使用FloodFill算法,结合深度优先搜索(DFS)和广度优先搜索(BFS),在8连通条件下计算网格中水池连通块的数量。提供了两种不同实现方式,包括带方向数组的BFS和不依赖方向的数组模拟队列。通过实例演示,展示了如何应用这些技术解决实际问题并优化代码结构。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1. 题目来源

链接:1097. 池塘计数

染色法求连通块中的个数:[bfs+dfs] lg-P1141 01迷宫(bfs+染色法求连通块+模板题)

2. 题目解析

FloodFill 第一种,求连通块个数。

本题是模板题,8 连通,dfsbfs 均可做。

提供多个版本的写法,都是常见的写法,务必熟练。


时间复杂度: O ( n m ) O(nm) O(nm)

空间复杂度: O ( n m ) O(nm) O(nm)


bfs + std::queue+方向数组

// std::queue
#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>
#include <algorithm>

using namespace std;

typedef pair<int, int> PII;

int dx[8] = {-1, -1, -1, 0, 1, 1, 1, 0}, dy[8] = {-1, 0, 1, 1, 1, 0, -1, -1};

const int N = 1005;

int n, m;
char g[N][N];
bool st[N][N];

void bfs(int sx, int sy) {
    queue<PII> q;
    q.push({sx, sy});
    st[sx][sy] = true;

    while (q.size()) {
        auto t = q.front(); q.pop();

        int x = t.first, y = t.second;
        for (int i = 0; i < 8; i ++ ) {
            int a = x + dx[i], b = y + dy[i];
            if (a < 0 || a >= n || b < 0 || b >= m || g[a][b] == '.' || st[a][b]) continue;

            q.push({a, b});
            st[a][b] = true;
        }
    }
}

int main() {
    scanf("%d%d", &n, &m);
    for (int i = 0; i < n; i ++ ) scanf("%s", g[i]);

    int res = 0;
    for (int i = 0; i < n; i ++ ) 
        for (int j = 0; j < m; j ++ )
            if (g[i][j] == 'W' && !st[i][j]) {
                bfs(i, j);
                res ++ ;
            }

    printf("%d\n", res);

    return 0;
}

针对 8 连通来讲,可以直接遍历当前格子的 9 方格,将本格子除掉即可,就不用定义方向数组了。

数组模拟队列+无方向数组 8 连通:

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

using namespace std;

typedef pair<int, int> PII;

const int N = 1005;

int n, m;
char g[N][N];
bool st[N][N];
PII q[N * N];

void bfs(int sx, int sy) {
    int hh = 0, tt = 0;
    q[0] = {sx, sy};
    st[sx][sy] = true;

    while (hh <= tt) {
        auto t = q[hh ++ ];

        int x = t.first, y = t.second;
        for (int i = x - 1; i <= x + 1; i ++ )          
            for (int j = y - 1; j <= y + 1; j ++ ) {
                if (i == x && j == y) continue;          // 遍历 9 格,遇到自己跳过即可
                if (i < 0 || i >= n || j < 0 || j >= m) continue;
                if (g[i][j] == '.' || st[i][j]) continue;

                q[ ++ tt ] = {i, j};
                st[i][j] = true;
            }
    }
}

int main() {
    scanf("%d%d", &n, &m);
    for (int i = 0; i < n; i ++ ) scanf("%s", g[i]);

    int res = 0;
    for (int i = 0; i < n; i ++ ) 
        for (int j = 0; j < m; j ++ )
            if (g[i][j] == 'W' && !st[i][j]) {
                bfs(i, j);
                res ++ ;
            }

    printf("%d\n", res);

    return 0;
}

dfs 写法,直接将连通块中的水池改为陆地,最后全为陆地,代码更短,但是貌似不容易理解了哈哈。

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

using namespace std;

const int N = 1005;

int dx[8] = {-1, -1, -1, 0, 1, 1, 1, 0}, dy[8] = {-1, 0, 1, 1, 1, 0, -1, -1};

int n, m;
char g[N][N];

void dfs(int sx, int sy) {
    g[sx][sy] = '.';
    for (int i = 0; i < 8; i ++ ) {
        int x = sx + dx[i], y = sy + dy[i];
        if (x >= 0 && x < n && y >= 0 && y <= m && g[x][y] == 'W') 
            dfs(x, y);
    }
}

int main() {
    scanf("%d%d", &n, &m);
    for (int i = 0; i < n; i ++ ) scanf("%s", g[i]);

    int res = 0;
    for (int i = 0; i < n; i ++ ) 
        for (int j = 0; j < m; j ++ )
            if (g[i][j] == 'W') {
                dfs(i, j);
                res ++ ;
            }

    printf("%d\n", res);

    return 0;
}
### Java矩阵上BFSDFS的实现 #### 广度优先搜索 (BFS) 广度优先搜索是一种逐层遍历的方式,通常借助队列来实现。以下是基于矩阵的BFS实现: ```java import java.util.LinkedList; import java.util.Queue; public class BFS { public void bfsTraversing(int[][] matrix, boolean[] visited, int startNode) { Queue<Integer> queue = new LinkedList<>(); queue.add(startNode); visited[startNode] = true; while (!queue.isEmpty()) { int currentNode = queue.poll(); System.out.print(currentNode + " "); for (int i = 0; i < matrix.length; i++) { if (matrix[currentNode][i] == 1 && !visited[i]) { queue.add(i); visited[i] = true; } } } } public static void main(String[] args) { int[][] adjacencyMatrix = { {0, 1, 1, 0}, {1, 0, 0, 1}, {1, 0, 0, 1}, {0, 1, 1, 0} }; boolean[] visited = new boolean[adjacencyMatrix.length]; BFS bfs = new BFS(); bfs.bfsTraversing(adjacencyMatrix, visited, 0); // 输出节点访问顺序 } } ``` 上述代码展示了如何通过邻接矩阵表示图并执行BFS操作[^1]。 --- #### 深度优先搜索 (DFS) 深度优先搜索采用递归方式或栈结构完成遍历过程。下面是基于矩阵的DFS实现: ```java public class DFS { public void dfsTraversing(int node, int[][] graph, boolean[] visited) { visited[node] = true; System.out.print(node + " "); for (int i = 0; i < graph.length; i++) { if (graph[node][i] == 1 && !visited[i]) { dfsTraversing(i, graph, visited); } } } public static void main(String[] args) { int[][] adjacencyMatrix = { {0, 1, 1, 0}, {1, 0, 0, 1}, {1, 0, 0, 1}, {0, 1, 1, 0} }; boolean[] visited = new boolean[adjacencyMatrix.length]; DFS dfs = new DFS(); dfs.dfsTraversing(0, adjacencyMatrix, visited); // 输出节点访问顺序 } } ``` 此代码片段实现了利用递归方式进行DFS的操作[^3]。 --- 对于LeetCode中的图像渲染问题,可以结合BFS/DFS解决二维数组的相关题目。例如给定初始坐标 `(sr, sc)` 和新颜色 `newColor`,可以通过修改像素值达到渲染效果[^2]。 ```java class Solution { private final int[][] directions = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}}; public int[][] floodFill(int[][] image, int sr, int sc, int color) { if (image[sr][sc] == color) return image; fill(image, sr, sc, image[sr][sc], color); return image; } private void fill(int[][] image, int r, int c, int oldColor, int newColor) { if (r < 0 || r >= image.length || c < 0 || c >= image[0].length || image[r][c] != oldColor) return; image[r][c] = newColor; for (int[] dir : directions) { fill(image, r + dir[0], c + dir[1], oldColor, newColor); } } } ``` 以上代码展示了一个典型的DFS应用案例——填充指定区域的颜色。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Ypuyu

如果帮助到你,可以请作者喝水~

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值