ARTICLE · 1504268
GESP七级备考系列(五)|泛洪算法(Flood Fill)精讲
GESP七级备考系列(五)|泛洪算法(Flood Fill)精讲
GESP七级备考系列 · 第5期
📌 本期关键词:Flood Fill、BFS、DFS、连通块、方向数组、岛屿统计
一、什么是泛洪算法(Flood Fill)?
🌊 一句话理解
从一个“种子点”出发,像洪水蔓延一样,沿着连通方向不断扩展,把所有满足条件的相邻格子“填充”或“标记”,直到无法继续扩展为止。
🎨 生活类比
想象你在用“画图”软件的油漆桶工具——点击一个像素点,与该点颜色相同且连通的所有区域被一次性替换为新颜色。这就是 Flood Fill!
📐 算法核心要素
| 种子点 | |
| 连通方向 | |
| 填充条件 | |
| 访问标记 | |
| 扩展方式 |
🔄 算法流程图
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
选择种子点(x, y)
│
▼
检查 (x, y) 是否满足填充条件 ──No──▶ 结束
│ Yes
▼
标记 (x, y) 已访问/填充
│
▼
┌─▶ 遍历方向数组
│ │
│ ▼
│ 计算邻居(nx, ny)
│ │
│ ▼
│ 未越界 & 满足条件 & 未访问?
│ │ Yes
│ ▼
│ 加入扩展队列/递归
│ │
└───────┘
│ 队列空/递归返回
▼
结束 Flood Fill 不是一种独立算法,而是一种“搜索+填充”的思想/模式,BFS 和 DFS 只是实现它的两种工具。
二、方向数组 dx/dy —— 连通扩展的核心技巧
🧭 方向数组的定义
方向数组是 Flood Fill 中最常用、也最优雅的技巧,用两组数组表示移动方向:
1 2 3 4 5 6 7
// 四连通:上、右、下、左
int dx[] = {-1, 0, 1, 0};
int dy[] = {0, 1, 0, -1};
// 八连通:上、右上、右、右下、下、左下、左、左上
int dx8[] = {-1, -1, 0, 1, 1, 1, 0, -1};
int dy8[] = {0, 1, 1, 1, 0, -1, -1, -1}; 📐 方向示意图
1 2 3 4
四连通: 八连通:
↑ ↖ ↑ ↗
← ● → ← ● →
↓ ↙ ↓ ↘ 💡 使用技巧
1 2 3 4 5 6
// 遍历四连通邻居
for (int i = 0; i < 4; i++) {
int nx = x + dx[i];
int ny = y + dy[i];
// 检查 nx, ny 是否合法
} ⚠️ 易错点:
dx和dy必须一一对应!第一个方向是dx[0]=-1, dy[0]=0(向上),写反会导致方向错乱。
三、边界检查与越界防护
每次计算邻居坐标后,必须进行边界检查,否则数组越界会导致运行时错误(RE)。
✅ 标准边界检查模板
1 2 3
bool isValid(int x, int y, int n, int m){
return x >= 0 && x < n && y >= 0 && y < m;
} 🔁 完整遍历邻居 + 边界检查
1 2 3 4 5 6 7 8
for (int i = 0; i < 4; i++) {
int nx = x + dx[i];
int ny = y + dy[i];
if (nx >= 0 && nx < n && ny >= 0 && ny < m
&& !visited[nx][ny] && grid[nx][ny] == target) {
// 扩展到
}
} 🚨 高频考点:选择题常考“以下哪种边界检查写法正确”,注意是
x >= 0 && x < n还是x > 0 && x <= n,取决于下标从0还是1开始。
四、BFS 实现 —— 队列驱动的层序填充
📋 算法思路
将种子点入队,标记为已访问 队头出队,检查四个方向的邻居 满足条件的邻居入队并标记 重复直到队列为空
💻 完整代码模板(BFS版)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
#include <iostream>
#include <queue>
#include <cstring>
using namespace std;
const int MAXN = 1005;
int grid[MAXN][MAXN]; // 网格
bool visited[MAXN][MAXN]; // 访问标记
int n, m;
int dx[] = {-1, 0, 1, 0}; // 四连通方向
int dy[] = {0, 1, 0, -1};
void floodFillBFS(int sx, int sy, int oldColor, int newColor){
if (grid[sx][sy] != oldColor) return; // 种子点不满足条件
queue<pair<int, int>> q;
q.push({sx, sy});
visited[sx][sy] = true;
grid[sx][sy] = newColor; // 填充新颜色
while (!q.empty()) {
pair<int,int> [x, y] = q.front();
q.pop();
int x = p.first;
int y = p.second;
for (int i = 0; i < 4; i++) {
int nx = x + dx[i];
int ny = y + dy[i];
if (nx >= 0 && nx < n && ny >= 0 && ny < m
&& !visited[nx][ny] && grid[nx][ny] == oldColor) {
visited[nx][ny] = true;
grid[nx][ny] = newColor; // 填充
q.push({nx, ny});
}
}
}
}
int main(){
cin >> n >> m;
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
cin >> grid[i][j];
memset(visited, false, sizeof(visited));
int sx, sy, newColor;
cin >> sx >> sy >> newColor;
floodFillBFS(sx, sy, grid[sx][sy], newColor);
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++)
cout << grid[i][j] << " ";
cout << "\n";
}
return 0;
} 💡 BFS 的关键细节
| 入队即标记 | visited,而不是出队时。否则同一格子可能被多次入队,导致重复处理甚至TLE |
| 就地修改 | grid 值代替 visited 数组,节省空间 |
| 时间复杂度 | |
| 空间复杂度 |
五、DFS 实现 —— 递归驱动的深度填充
📋 算法思路
访问当前格子,标记为已访问并填充 递归地对四个方向的邻居执行同样的操作 递归天然“回溯”,无需显式维护栈
💻 完整代码模板(DFS版)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
#include <iostream>
#include <cstring>
using namespace std;
const int MAXN = 1005;
int grid[MAXN][MAXN];
bool visited[MAXN][MAXN];
int n, m;
int dx[] = {-1, 0, 1, 0};
int dy[] = {0, 1, 0, -1};
void floodFillDFS(int x, int y, int oldColor, int newColor){
// 边界检查
if (x < 0 || x >= n || y < 0 || y >= m) return;
// 条件检查
if (visited[x][y] || grid[x][y] != oldColor) return;
// 标记并填充
visited[x][y] = true;
grid[x][y] = newColor;
// 递归四个方向
for (int i = 0; i < 4; i++) {
floodFillDFS(x + dx[i], y + dy[i], oldColor, newColor);
}
}
int main(){
cin >> n >> m;
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
cin >> grid[i][j];
memset(visited, false, sizeof(visited));
int sx, sy, newColor;
cin >> sx >> sy >> newColor;
floodFillDFS(sx, sy, grid[sx][sy], newColor);
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++)
cout << grid[i][j] << " ";
cout << "\n";
}
return 0;
} 💡 DFS 的关键细节
| 递归深度 | |
| 代码简洁 | |
| 就地修改 | visited,直接修改 grid |
| 回溯注意 |
六、BFS vs DFS —— 优劣对比
⚔️ 全面对比表
| 数据结构 | queue | |
| 扩展顺序 | ||
| 栈溢出风险 | ||
| 空间开销 | ||
| 代码复杂度 | ||
| 最短路径 | ||
| GESP推荐 | ||
| 时间复杂度 |
🎯 考试策略建议
- 网格规模 ≤ 50×50: DFS 和 BFS 都可以,DFS 写起来更快
- 网格规模 > 100×100: 强烈建议用 BFS,避免栈溢出
- 需要最短距离: 必须用 BFS
- GESP七级考试: 题目网格通常在 100×100 以内,但保险起见优先 BFS
七、四连通 vs 八连通
🔲 四连通(4-Connected)
只有上下左右四个方向相邻才算连通。
1 2 3
■
■ ★ ■
■ 🔲 八连通(8-Connected)
上下左右 + 四个对角线方向,共八个方向。
1 2 3
■ ■ ■
■ ★ ■
■ ■ ■ 💻 代码差异
1 2 3 4 5 6 7 8 9
// 四连通
int dx4[] = {-1, 0, 1, 0};
int dy4[] = {0, 1, 0, -1};
// 循环 4 次: for (int i = 0; i < 4; i++)
// 八连通
int dx8[] = {-1, -1, 0, 1, 1, 1, 0, -1};
int dy8[] = {0, 1, 1, 1, 0, -1, -1, -1};
// 循环 8 次: for (int i = 0; i < 8; i++) 仅需修改方向数组和循环次数,其余代码完全一致!
⚠️ 易错点
| 连通定义不同导致结果不同 | |
| 对角线接触 | |
| 考试陷阱 |
八、经典应用场景
🏝️ 应用一:岛屿数量统计
题目描述:给定一个 n×m 的 01 矩阵,1 代表陆地,0 代表水。上下左右相连的 1 组成一个岛屿。求岛屿数量。
思路:遍历整个网格,每发现一个未访问的 1,就启动一次 Flood Fill(标记整个岛屿),岛屿计数 +1。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
#include <iostream>
#include <queue>
#include <cstring>
using namespace std;
const int MAXN = 1005;
int grid[MAXN][MAXN];
bool visited[MAXN][MAXN];
int n, m;
int dx[] = {-1, 0, 1, 0};
int dy[] = {0, 1, 0, -1};
void bfs(int sx, int sy){
queue<pair<int,int>> q;
q.push({sx, sy});
visited[sx][sy] = true;
while (!q.empty()) {
auto [x, y] = q.front(); q.pop();
for (int i = 0; i < 4; i++) {
int nx = x + dx[i], ny = y + dy[i];
if (nx >= 0 && nx < n && ny >= 0 && ny < m
&& !visited[nx][ny] && grid[nx][ny] == 1) {
visited[nx][ny] = true;
q.push({nx, ny});
}
}
}
}
int main(){
cin >> n >> m;
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
cin >> grid[i][j];
memset(visited, false, sizeof(visited));
int islandCount = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (grid[i][j] == 1 && !visited[i][j]) {
bfs(i, j); // 填充整个岛屿
islandCount++; // 岛屿数 +1
}
}
}
cout << islandCount << endl;
return 0;
} 📐 应用二:最大连通块面积
思路:在 BFS/DFS 过程中统计扩展的格子数量,取所有连通块中的最大值。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
int bfsArea(int sx, int sy){
queue<pair<int,int>> q;
q.push({sx, sy});
visited[sx][sy] = true;
int area = 0;
while (!q.empty()) {
auto [x, y] = q.front(); q.pop();
area++; // 每出队一个格子,面积+1
for (int i = 0; i < 4; i++) {
int nx = x + dx[i], ny = y + dy[i];
if (nx >= 0 && nx < n && ny >= 0 && ny < m
&& !visited[nx][ny] && grid[nx][ny] == 1) {
visited[nx][ny] = true;
q.push({nx, ny});
}
}
}
return area;
}
// 主函数中:
int maxArea = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (grid[i][j] == 1 && !visited[i][j]) {
maxArea = max(maxArea, bfsArea(i, j));
}
}
}
cout << maxArea << endl; 🎨 应用三:图像填充(油漆桶)
思路:从点击位置出发,将所有连通的同色像素替换为新颜色。这是 Flood Fill 最原始的应用场景。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
void floodFill(int sx, int sy, int newColor){
int oldColor = image[sx][sy];
if (oldColor == newColor) return; // 颜色相同直接返回,避免无限循环!
queue<pair<int,int>> q;
q.push({sx, sy});
image[sx][sy] = newColor;
while (!q.empty()) {
auto [x, y] = q.front(); q.pop();
for (int i = 0; i < 4; i++) {
int nx = x + dx[i], ny = y + dy[i];
if (nx >= 0 && nx < n && ny >= 0 && ny < m
&& image[nx][ny] == oldColor) {
image[nx][ny] = newColor;
q.push({nx, ny});
}
}
}
} 🚨 高频易错:当
oldColor == newColor时必须直接返回!否则会陷入无限循环(因为填充后仍满足条件)。
🧩 应用四:迷宫区域标记
思路:从起点出发进行 Flood Fill,将可达区域全部标记,用于判断某点是否可达或计算可达区域大小。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
void markReachable(int sx, int sy){
// grid中: 0=可通行, 1=墙壁
queue<pair<int,int>> q;
q.push({sx, sy});
visited[sx][sy] = true;
while (!q.empty()) {
auto [x, y] = q.front(); q.pop();
for (int i = 0; i < 4; i++) {
int nx = x + dx[i], ny = y + dy[i];
if (nx >= 0 && nx < n && ny >= 0 && ny < m
&& !visited[nx][ny] && grid[nx][ny] == 0) {
visited[nx][ny] = true;
q.push({nx, ny});
}
}
}
// 之后遍历 visited 数组即可知道哪些格子从起点可达
} 九、变式题型
🌈 变式一:多色填充
场景:网格中不止两种值,需要将所有连通的同值区域分别标记为不同编号。
1 2 3 4 5 6 7 8 9 10 11
int regionId = 0; // 区域编号
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (!visited[i][j]) {
regionId++;
int color = grid[i][j];
bfs(i, j, color, regionId); // 从出发,填充同color的连通区域
}
}
}
// regionId 即为不同颜色区域的总数 🎯 变式二:带条件填充
场景:不是填充相同值,而是填充满足某种条件的格子(如值在某个范围内、值大于阈值等)。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
// 示例:填充所有值 >= threshold 的连通格子
void conditionalFloodFill(int sx, int sy, int threshold){
queue<pair<int,int>> q;
q.push({sx, sy});
visited[sx][sy] = true;
while (!q.empty()) {
auto [x, y] = q.front(); q.pop();
for (int i = 0; i < 4; i++) {
int nx = x + dx[i], ny = y + dy[i];
if (nx >= 0 && nx < n && ny >= 0 && ny < m
&& !visited[nx][ny] && grid[nx][ny] >= threshold) {
visited[nx][ny] = true;
q.push({nx, ny});
}
}
}
} 🔢 变式三:区域计数 + 区域属性统计
场景:统计连通块数量,并同时记录每个连通块的面积、周长等属性。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
struct Region {
int id;
int area;
int perimeter;
};
vector<Region> regions;
void bfsAndRecord(int sx, int sy, int regionId){
queue<pair<int,int>> q;
q.push({sx, sy});
visited[sx][sy] = true;
int area = 0, perimeter = 0;
while (!q.empty()) {
auto [x, y] = q.front(); q.pop();
area++;
for (int i = 0; i < 4; i++) {
int nx = x + dx[i], ny = y + dy[i];
if (nx < 0 || nx >= n || ny < 0 || ny >= m || grid[nx][ny] == 0) {
perimeter++; // 边界或墙壁贡献周长
} else if (!visited[nx][ny] && grid[nx][ny] == 1) {
visited[nx][ny] = true;
q.push({nx, ny});
}
}
}
regions.push_back({regionId, area, perimeter});
} 十、高频易错点总结
🚨 考试十大易错点
| 入队时立即标记 | ||
< 写成 <=) | x >= 0 && x < n | |
!visited[i][j] | ||
十一、考试常见考法
📝 选择题常见考法
- 方向数组判断: 给出
dx[]={-1,0,1,0}, dy[]={0,1,0,-1},问表示什么方向 → 四连通(上下左右) - 复杂度判断: Flood Fill 的时间复杂度为 O(n×m) ✓
- 连通性判断: 给定一个网格,问四连通和八连通下的连通块数量
- BFS/DFS特征: 以下关于BFS实现Flood Fill的说法正确的是?(入队时标记visited)
- 栈溢出判断: 在 1000×1000 网格上用递归DFS实现Flood Fill,可能出现什么问题?(栈溢出)
✅ 判断题常见考法
Flood Fill算法只能用BFS实现(✗,DFS也可以) 四连通一定比八连通的连通块数量多或相等(✓) BFS实现Flood Fill时,应该在出队时标记visited(✗,应在入队时标记) 如果填充颜色与原颜色相同,Flood Fill会陷入死循环(✓,需特判) Flood Fill的时间复杂度与网格大小有关,与种子点位置无关(✓)
💻 编程题常见考法
- 岛屿数量/最大岛屿面积: 最经典的 Flood Fill 编程题
- 图像填充: 给定种子点和颜色,输出填充后的图像
- 区域统计: 统计不同区域数量及各自属性
- 连通块判断: 判断两个点是否在同一连通块中
🌟 Flood Fill 考试口诀
- 入队即标记,出队再标记必 TLE
- oldColor 同 newColor,不特判就死循环
- 大网格用 BFS,小网格 DFS 随意
- 方向数组 dx dy,一一对应别写反
- 四连通八连通,审题第一要记牢
十二、练习题
📝 练习一(选择题)
题目:在一个 5×5 的 01 矩阵中,1 表示陆地。使用四连通 Flood Fill 统计岛屿数量,以下哪种说法正确?
A. BFS和DFS实现的结果可能不同
B. 每次Flood Fill会将一个岛屿的所有格子标记为已访问
C. 统计岛屿数量时,需要将visited数组在每次Flood Fill后重置
D. 如果使用八连通,岛屿数量一定比四连通少
📝 练习二(判断题)
题目:在使用递归 DFS 实现 Flood Fill 时,如果网格大小为 1000×1000 且全部需要填充,则程序一定会因为栈溢出而崩溃。
十三、备考建议与平台推荐
📚 备考建议
- 先理解再编码: Flood Fill 的核心就是“从一个点出发,向连通方向扩展”,理解了这个思想,代码模板自然水到渠成
- 背熟 BFS 模板: BFS 版本更安全(无栈溢出风险),是考试首选
- 注意特判:
oldColor == newColor的陷阱一定要记住 - 多刷变式题: 岛屿数量、最大面积、区域计数等变式,本质上都是同一个模板的不同应用
- 手画模拟: 考试中遇到选择题,画一个小网格手动模拟 Flood Fill 过程
🌟 平台推荐
想要更多 Flood Fill 练习题?推荐使用 百练百会(www.bestwit.cn) 平台:
✅ 提供 GESP 各级别专项练习,覆盖 Flood Fill 等七级核心考点 ✅ 在线判题,即时反馈,帮你快速定位代码问题 ✅ 题目难度梯度合理,从基础模板题到变式应用题一应俱全 ✅ 适合备考冲刺阶段集中刷题,巩固算法模板
💡 建议在百练百会上至少刷 5-8 道 Flood Fill 相关题目,确保模板熟练到“默写”级别!
练习题答案
练习一(选择题) 答案:B
解析:
A错误:BFS和DFS只是扩展顺序不同,最终标记的连通区域完全相同 B正确:每次Flood Fill正是将一个完整岛屿的所有格子标记为已访问 C错误:visited数组在所有Flood Fill过程中共享,不需要重置。每次外层循环检查 !visited[i][j]即可D错误:八连通的岛屿数量小于或等于四连通(因为更多方向可能合并岛屿),但“一定少”太绝对,若所有岛屿互不相邻则两者相同
练习二(判断题)答案:错误(✗)
解析:
“一定会”过于绝对。是否栈溢出取决于系统的栈大小设置、编译器优化等 在大多数默认环境下,1000×1000 网格的 DFS 递归深度可能达到数千层,确实极可能栈溢出。当然,具体递归深度与方向数组顺序和起始点有关,全填充网格下约为 O(n+m) 层。 但如果通过 #pragma comment(linker, "/STACK:102400000,102400000")手动扩栈,或改用 BFS 实现,则可以避免栈溢出。考试中判断题遇到“一定”“必然”等绝对化表述,通常需要谨慎
📢 下期预告
GESP七级备考系列(六)|哈希表精讲
下期将介绍哈希表的核心概念:哈希函数、冲突处理(链地址法/开放寻址法)、负载因子、常用哈希操作,以及 GESP 七级考试中的高频考法。敬请期待!🎉
📌 关注本系列,GESP七级备考不迷路!如有疑问,欢迎在评论区交流。
本文为 GESP 七级备考系列第5期,系列持续更新中。
百练百会 一站式 GESP 备考平台 个人独立运营、非盈利免费学习工具
网页端官网:www.bestwit.cn 网页端 + 微信小程序数据双向同步 微信小程序/公众号:搜索名称「百练百会」 
百练百会GESP备考平台介绍















































































