Flood Fill 算法:数字世界的颜料蔓延术
算法本质 一种用于填充连通区域的经典算法,通过指定起点和填充规则,像倒颜料般自动填满封闭区域。
核心思想
- 选定起点:从像素/网格的某个点出发
- 扩散规则:
- 4 连通:上下左右 4 个方向
- 8 连通:增加斜向共 8 个方向(更易漏边)
- 停止条件:遇到边界色或已填充区域
两种经典实现
基础版(DFS 递归实现)
#include <vector>
#include <iostream>
using namespace std;
// 4 方向移动:上右下左
const int dx[] = {-1, 0, 1, 0};
const int dy[] = {0, 1, 0, -1};
void dfs(vector<vector<int>>& image, int x, int y, int oldColor, int newColor) {
// 边界检查 + 颜色检查
if(x < 0 || x >= image.size() || y < 0 || y >= image[0].size() || image[x][y] != oldColor || image[x][y] == newColor) return;
image[x][y] = newColor;
// 填充新颜色
// 递归 4 个方向
( i = ; i < ; ++i) {
(image, x + dx[i], y + dy[i], oldColor, newColor);
}
}
vector<vector<>> (vector<vector<>>& image, sr, sc, newColor) {
oldColor = image[sr][sc];
(oldColor != newColor) (image, sr, sc, oldColor, newColor);
image;
}








