# 泛洪填充

**泛洪填充**（Flood fill）是一种算法，用于确定网格或图像中包含给定种子单元格的同值单元格连通区域，并将它们全部改为新值；它正是图像编辑器中油漆桶工具背后的操作。算法从种子像素出发，向颜色或亮度匹配目标值的相邻像素扩散并重新着色，遇到不匹配的像素或指定边界时停止。<sup>[1](https://bytepatterns.com/blog/flood-fill-algorithm-dfs-bfs-explained)</sup>

| 关键事实 | 详情 |
|---|---|
| 功能 | 重新着色种子单元格以及通过上、下、左、右四个方向与它相连的、具有相同原始颜色的所有单元格；无法到达的同色区块保持不变<sup>[1](https://bytepatterns.com/blog/flood-fill-algorithm-dfs-bfs-explained)</sup> |
| 连通性 | 4连通填充考虑共享一条边的四个邻居；8连通填充还考虑共享一个角的四个对角邻居<sup>[2](https://docs.opencv.org/2.4.13.7/modules/imgproc/doc/miscellaneous_transformations.html?highlight=floodfill)</sup> |
| 时间复杂度 | 与填充区域的像素数成正比；对于 m × n 的网格，每个单元格最多被处理四次，因此为 O(mn)<sup>[3](https://stackoverflow.com/questions/29160614/flood-fill-four-way-algorithm-complexity)</sup> |
| 主要实现风险 | 朴素递归每处理一个像素就递归一次，在大图像上可能导致调用栈溢出；基于迭代的栈或队列版本以及扫描线变体可以避免此问题<sup>[4](https://stackoverflow.com/questions/274213/how-does-the-fill-operation-work-in-paint-applications)</sup> |
| 标准库支持 | OpenCV 的 `floodFill`、MATLAB 的 `imfill` 和 Pillow 的 `ImageDraw.floodfill` 都实现了该操作，并可配置连通性和颜色容差<sup>[2](https://docs.opencv.org/2.4.13.7/modules/imgproc/doc/miscellaneous_transformations.html?highlight=floodfill)</sup><sup> • </sup><sup>[5](https://www.mathworks.com/help/images/flood-fill-operations.html)</sup><sup> • </sup><sup>[6](https://pillow.readthedocs.io/en/stable/reference/ImageDraw.html?highlight=shape)</sup> |
| 有记载的历史 | 迪克·舒普（Dick Shoup）在20世纪70年代中期为其 SuperPaint 系统实现了一种填充技术；阿尔维·雷·史密斯（Alvy Ray Smith）的24位泛洪填充和色调填充算法发表于1979年的 SIGGRAPH<sup>[7](https://www.researchgate.net/publication/3208913_Fill_%27er_up_Graphics_filling_algorithms)</sup> |

## 它解决的问题

输入是一个颜色网格、一个起始单元格和一个新颜色。结果会重新着色初始单元格，以及从它出发通过四方向移动（上、下、左、右）可达的所有同色单元格。那些不跨越不同颜色就无法到达的同色单元格保持原样；正是这种可达性条件——而非简单遍历网格——将泛洪填充与全局颜色替换区分开来。<sup>[1](https://bytepatterns.com/blog/flood-fill-algorithm-dfs-bfs-explained)</sup>

用图形学术语来说，如果已知区域内部的一个种子点，填充可以用递归完成。一个经典的教科书版本将多边形的边以边颜色扫描到帧缓冲区中，然后填充仍然保持背景色的内部像素：<sup>[8](https://www.cs.kent.edu/~farrell/cg05/lectures/cg25.pdf)</sup>

```
flood_fill(int x, int y) {
  if (read_pixel(x, y) == WHITE) {
    write_pixel(x, y, BLACK);
    flood_fill(x-1, y);
    flood_fill(x+1, y);
    flood_fill(x, y+1);
    flood_fill(x, y-1);
  }
}
```

同一过程也可以用显式栈来表达：将种子压栈，然后反复弹出一个像素，应用填充色，并将每个颜色仍与内部色匹配的相连像素压栈，直到栈为空。邻居测试可以考虑4个连通像素或8个连通像素。<sup>[9](https://www.iitg.ac.in/samit/Computer%20Graphics.pdf)</sup> 选择栈使遍历为深度优先；选择队列则使其为广度优先，但两者访问的连通区域完全相同。<sup>[1](https://bytepatterns.com/blog/flood-fill-algorithm-dfs-bfs-explained)</sup>

## 连通性与容差

填充区域的形状取决于邻居的定义方式。OpenCV 的 `floodFill` 接受一个连通性标志，默认值4表示只考虑共享一条边的四个最近邻像素；值8表示考虑共享一个角的八个最近邻像素。<sup>[2](https://docs.opencv.org/2.4.13.7/modules/imgproc/doc/miscellaneous_transformations.html?highlight=floodfill)</sup>

真实图像很少有完全均匀的区域，因此实际实现会加入容差。OpenCV 接受亮度或颜色差的下界和上界 `loDiff` 和 `upDiff`，当像素值相对于已在连通分量中的邻居的值（浮动范围）或种子像素本身的值（`FLOODFILL_FIXED_RANGE` 选项）的差异在这些界限之内时，该像素加入重新着色的区域。`FLOODFILL_MASK_ONLY` 标志填充一个辅助掩码而不改变图像。Pillow 的 `ImageDraw.floodfill` 同样接受一个 `thresh` 参数，指定像素值与背景之间可容忍的最大差值，适用于填充颜色不均匀但相近的区域，还有一个可选的 `border` 参数，将区域定义为与边界颜色不同的像素。<sup>[2](https://docs.opencv.org/2.4.13.7/modules/imgproc/doc/miscellaneous_transformations.html?highlight=floodfill)</sup><sup> • </sup><sup>[6](https://pillow.readthedocs.io/en/stable/reference/ImageDraw.html?highlight=shape)</sup>

连通性的选择也会改变什么算作封闭。在 MATLAB 中，`imfill` 对背景像素操作，连通性参数指定的是背景的连通性，而非前景。对于4连通背景，一个环形图像包含两个独立的背景元素——环内部分和环外部分——因此从环内种子填充只填充内部；对于8连通背景，同一种子会填充整个图像，因为背景通过对角线泄漏了。专用的 `imfill(BW,"holes")` 语法填充每个孔洞，其中孔洞是指从图像边界开始填充背景时无法到达的背景像素。<sup>[5](https://www.mathworks.com/help/images/flood-fill-operations.html)</sup>

## 性能与实现变体

时间复杂度与填充区域的像素数成正比：对于有 M 个像素、边长为 N 的正方形区域，M = N²，复杂度为 O(M) = O(N²)。就网格而言，每个单元格可能被其上、下、左、右邻居调用，因此每个单元格最多被处理四次，上界为 O(mn)。<sup>[3](https://stackoverflow.com/questions/29160614/flood-fill-four-way-algorithm-complexity)</sup>

**实际限制是栈深度，而非时间。** 对于大图像，朴素递归版本很可能因为对每个像素递归而出现栈溢出错误。一种常见的改进是在填充一行像素时使用迭代，然后递归填充上方和下方的行。<sup>[4](https://stackoverflow.com/questions/274213/how-does-the-fill-operation-work-in-paint-applications)</sup> 从业者在游戏开发中也报告了同样的经验：迭代方案比递归方案快得多，而递归函数只能调用有限次数，之后就会出现栈溢出异常。<sup>[10](https://forum.defold.com/t/flood-fill-algorithm/63864)</sup>

基于跨度的变体进一步减少内存。扫描线方法一次填充整段水平连续像素，而三维扫描线种子填充算法沿扫描线一次压入或弹出更多种子，并且只压入最右侧的种子，降低了重复种子搜索和栈操作的频率，并减少了内存消耗；普通的递归泛洪填充反复访问每个种子并且一次只弹出一个种子，导致大量内存和时间消耗，在处理大型三维区域时可能耗尽内存。<sup>[11](https://www.sciencedirect.com/science/article/abs/pii/S0097849310000725)</sup> 1993年对高效泛洪填充算法的分析证明，一种代表性算法所需的工作内存与待填充区域包围盒的水平尺寸成正比，并且该算法能处理由边界或内部定义的4连通和8连通区域。<sup>[12](https://www.sciencedirect.com/science/article/pii/009784939390006u/pdf)</sup>

泛洪填充是区域填充算法的两大类别之一，另一类是边缘填充或扫描线填充，它根据多边形的几何形状而非从种子生长来计算区域。扫描线多边形填充算法假定区域由顶点和边定义，将每条扫描线与所有边求交，按 x 坐标递增对交点排序，并填充由交点奇偶性确定的跨度。<sup>[9](https://www.iitg.ac.in/samit/Computer%20Graphics.pdf)</sup><sup> • </sup><sup>[8](https://www.cs.kent.edu/~farrell/cg05/lectures/cg25.pdf)</sup>

## 应用

**绘画程序。** 泛洪填充就是用户在编辑器中打开图像并点击油漆桶工具时发生的事情。<sup>[13](https://stackoverflow.blog/2020/07/08/improving-performance-with-simd-intrinsics-in-three-use-cases/)</sup> 最早有记载的填充例程可追溯到20世纪70年代中期：迪克·舒普为其 SuperPaint 系统实现了一种填充技术，而阿尔维·雷·史密斯——皮克斯联合创始人、纽约理工学院首个全彩 RGB 电子绘画程序的作者——发表了一种24位泛洪填充算法，其中还包含色调填充。<sup>[7](https://www.researchgate.net/publication/3208913_Fill_%27er_up_Graphics_filling_algorithms)</sup><sup> • </sup><sup>[14](https://alvyray.com/Bio/BioCV.htm)</sup> 史密斯1979年的 SIGGRAPH 论文《色调填充》解决了边界有明暗变化的区域的更难问题，例如被数字化照片或抗锯齿线条产生的多种灰度曲线包围的白色区域，此时填充应保持明暗关系，用新颜色的各种色调替代旧的。<sup>[15](https://www.researchgate.net/publication/234761617_Tint_fill)</sup>

**图像分析。** 从一个选定的种子像素出发，泛洪填充向外扩展到每个值相近的连通邻居；该任务的全图版本——连通分量标记——则扫描整个图像，为每个斑块分配各自的整数标签，无需手动选择种子。<sup>[16](https://sbirchfield.github.io/cvintro/lessons/lesson04_floodfill_connected_components.html)</sup> 用 `imfill` 进行孔洞填充是二值和灰度图像的标准预处理步骤。<sup>[5](https://www.mathworks.com/help/images/flood-fill-operations.html)</sup>

**地形分析。** 优先泛洪算法将泛洪应用于数字高程模型，使用按高程递增排序的优先队列从边缘向内淹没地形，确保每个单元格都能排水；对于整数数据它以 O(n) 时间运行，适用于不规则网格以及4、6、8和 n 连通网格，其改进变体在测试中比原始版本快达37%。<sup>[17](https://arxiv.org/abs/1511.04463)</sup>

**机器学习。** 泛洪填充网络用单个循环三维卷积网络取代了传统的两步分割流程（先边界检测再像素分组），直接从原始图像产生各个分割段，以泛洪填充的方式生长分割段；在基于三维电子显微镜数据的连接组重建中，它们大幅提高了相对于其他最先进方法的准确率。<sup>[18](https://arxiv.org/abs/1611.00421)</sup>

## 作为计算问题的泛洪填充

同样的区域生长操作定义了组合游戏 Flood-It，玩家反复将与一个枢轴瓦片相连的单色区域重新着色，以最少的步数使整个棋盘变为单色。对于 c ≥ 3 种颜色，寻找最少泛洪操作次数是 NP 难的，即使对于可以从任意位置开始泛洪的自由变体也是如此，而自由变体在 c = 2 时属于 P。当颜色数不受限制时，Flood-It 在高度为3或以上的棋盘上仍是 NP 难的，而只有2行高的棋盘可以在多项式时间内求解，最难的 n × n 实例需要 Θ(n·c<sup>0.5</sup>) 步。<sup>[19](https://arxiv.org/abs/1001.4420)</sup> 在树上，即使限制为3色树，Flood-It 仍是 NP 难的。<sup>[20](https://www.sciencedirect.com/science/article/pii/S030439751500105X)</sup>

## References

1. [Flood Fill Algorithm Explained: DFS, BFS and the Same-Colour Trap, BytePatterns](https://bytepatterns.com/blog/flood-fill-algorithm-dfs-bfs-explained)
2. [Miscellaneous Image Transformations (floodFill), OpenCV 2.4.13.7 documentation](https://docs.opencv.org/2.4.13.7/modules/imgproc/doc/miscellaneous_transformations.html?highlight=floodfill)
3. [Flood Fill Four-Way Algorithm Complexity, Stack Overflow](https://stackoverflow.com/questions/29160614/flood-fill-four-way-algorithm-complexity)
4. [How does the fill operation work in paint applications?, Stack Overflow](https://stackoverflow.com/questions/274213/how-does-the-fill-operation-work-in-paint-applications)
5. [Flood-Fill Operations, MATLAB & Simulink documentation](https://www.mathworks.com/help/images/flood-fill-operations.html)
6. [ImageDraw module, Pillow (PIL Fork) documentation](https://pillow.readthedocs.io/en/stable/reference/ImageDraw.html?highlight=shape)
7. [Fill 'er up! Graphics filling algorithms, IEEE Computer Graphics and Applications](https://www.researchgate.net/publication/3208913_Fill_%27er_up_Graphics_filling_algorithms)
8. [Implementation lecture notes (Flood Fill, Scan Line Fill), Kent State University](https://www.cs.kent.edu/~farrell/cg05/lectures/cg25.pdf)
9. [Computer Graphics, Samit Bhattacharya, IIT Guwahati (Chapter 9, Seed Fill and Scan Line Polygon Fill)](https://www.iitg.ac.in/samit/Computer%20Graphics.pdf)
10. [Flood Fill Algorithm, Defold game engine forum](https://forum.defold.com/t/flood-fill-algorithm/63864)
11. [A rapid 3D seed-filling algorithm based on scan slice, Computers & Graphics](https://www.sciencedirect.com/science/article/abs/pii/S0097849310000725)
12. [An efficient flood-filling algorithm, Burtsev & Kuzmin, Computers & Graphics 17(5), 1993](https://www.sciencedirect.com/science/article/pii/009784939390006u/pdf)
13. [Improving performance with SIMD intrinsics in three use cases, Stack Overflow Blog](https://stackoverflow.blog/2020/07/08/improving-performance-with-simd-intrinsics-in-three-use-cases/)
14. [Dr Alvy Ray Smith Curriculum Vitae](https://alvyray.com/Bio/BioCV.htm)
15. [Tint fill, Alvy Ray Smith, SIGGRAPH 1979](https://www.researchgate.net/publication/234761617_Tint_fill)
16. [Lesson 4: Flood Fill and Connected Components, Introduction to Computer Vision](https://sbirchfield.github.io/cvintro/lessons/lesson04_floodfill_connected_components.html)
17. [Priority-Flood: An Optimal Depression-Filling and Watershed-Labeling Algorithm for Digital Elevation Models, arXiv](https://arxiv.org/abs/1511.04463)
18. [Flood-Filling Networks, Januszewski et al., arXiv 2016](https://arxiv.org/abs/1611.00421)
19. [The Complexity of Flood Filling Games, Clifford, Jalsenius, Montanaro, Sach, arXiv 2010](https://arxiv.org/abs/1001.4420)
20. [Tractability and hardness of flood-filling games on trees, Theoretical Computer Science](https://www.sciencedirect.com/science/article/pii/S030439751500105X)

---
*Initially written Sep 17, 2026 · Reviewed: Oct 15, 2026 · Edited: Oct 15, 2026 · Last review: Oct 15, 2026*

Topic: 物质世界与数学 › 数学与统计学 › 逻辑与离散数学 › General discrete mathematics and discrete structures › Graph theory › Computational graph problems and algorithms › Graph traversal and search

Copyright 2026 Edgepedia

License: Edgepedia Community License 1.0, https://www.edgepedia.org/edgepedia/license

Source: https://www.edgepedia.org/zh/flood-fill

English original: https://www.edgepedia.org/flood-fill
