LeetCode 题解工作台
图像渲染
有一幅以 m x n 的二维整数数组表示的图画 image ,其中 image[i][j] 表示该图画的像素值大小。你也被给予三个整数 sr , sc 和 color 。你应该从像素 image[sr][sc] 开始对图像进行上色 填充 。 为了完成 上色工作 : 从初始像素开始,将其颜色改为 co…
4
题型
6
代码语言
3
相关题
当前训练重点
简单 · 图·搜索
答案摘要
我们记初始像素的颜色为 ,如果 不等于目标颜色 ,我们就从 $(\textit{sr}, \textit{sc})$ 开始深度优先搜索,将所有符合条件的像素点的颜色都更改成目标颜色。 时间复杂度 $O(m \times n)$,空间复杂度 $O(m \times n)$。其中 和 分别为二维数组 的行数和列数。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 图·搜索 题型思路
题目描述
有一幅以 m x n 的二维整数数组表示的图画 image ,其中 image[i][j] 表示该图画的像素值大小。你也被给予三个整数 sr , sc 和 color 。你应该从像素 image[sr][sc] 开始对图像进行上色 填充 。
为了完成 上色工作:
- 从初始像素开始,将其颜色改为
color。 - 对初始坐标的 上下左右四个方向上 相邻且与初始像素的原始颜色同色的像素点执行相同操作。
- 通过检查与初始像素的原始颜色相同的相邻像素并修改其颜色来继续 重复 此过程。
- 当 没有 其它原始颜色的相邻像素时 停止 操作。
最后返回经过上色渲染 修改 后的图像 。
示例 1:

(sr,sc)=(1,1) (即红色像素),在路径上所有符合条件的像素点的颜色都被更改成相同的新颜色(即蓝色像素)。示例 2:
提示:
m == image.lengthn == image[i].length1 <= m, n <= 500 <= image[i][j], color < 2160 <= sr < m0 <= sc < n
解题思路
方法一:DFS
我们记初始像素的颜色为 ,如果 不等于目标颜色 ,我们就从 开始深度优先搜索,将所有符合条件的像素点的颜色都更改成目标颜色。
时间复杂度 ,空间复杂度 。其中 和 分别为二维数组 的行数和列数。
class Solution:
def floodFill(
self, image: List[List[int]], sr: int, sc: int, color: int
) -> List[List[int]]:
def dfs(i: int, j: int):
image[i][j] = color
for a, b in pairwise(dirs):
x, y = i + a, j + b
if 0 <= x < len(image) and 0 <= y < len(image[0]) and image[x][y] == oc:
dfs(x, y)
oc = image[sr][sc]
if oc != color:
dirs = (-1, 0, 1, 0, -1)
dfs(sr, sc)
return image
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is O(N) where N is total pixels, as each pixel is visited once. Space complexity is O(N) in worst case due to recursion stack or queue storage. |
| 空间 | O(N) |
面试官常问的追问
外企场景- question_mark
Checks if you recognize that a recursive DFS naturally models connected components in a grid.
- question_mark
Looks for handling of edge conditions like starting pixel already having target color.
- question_mark
Wants to see whether BFS alternative is considered for avoiding deep recursion stack.
常见陷阱
外企场景- error
Modifying pixels before checking color can paint unintended areas.
- error
Failing to handle the starting pixel being the same as the target color can cause infinite recursion.
- error
Ignoring boundary conditions leads to index errors.
进阶变体
外企场景- arrow_right_alt
Use DFS with diagonal connections to extend flood fill to 8-direction connectivity.
- arrow_right_alt
Perform flood fill on a 3D matrix for volumetric image processing.
- arrow_right_alt
Implement color replacement with constraints, such as only changing pixels within a certain distance.