733. Flood Fill
At a Glance
- Topic: Graph
- Pattern: DFS / BFS
- Difficulty: Easy
- LeetCode: 733
Problem Statement
You are given an image represented by an m x n grid of integers image, where image[i][j] represents the pixel value of the image. You are also given three integers sr, sc, and color. Your task is to perform a flood fill on the image starting from the pixel image[sr][sc].
To perform a flood fill:
Begin with the starting pixel and change its color to color.
Perform the same process for each pixel that is directly adjacent (pixels that share a side with the original pixel, either horizontally or vertically) and shares the same color as the starting pixel.
Keep repeating this process by checking neighboring pixels of the updated pixels and modifying their color if it matches the original color of the starting pixel.
The process stops when there are no more adjacent pixels of the original color to update.Return the modified image after performing the flood fill.
Example 1:
Input: image = [[1,1,1],[1,1,0],[1,0,1]], sr = 1, sc = 1, color = 2
Output: [[2,2,2],[2,2,0],[2,0,1]]
...
Approach & Solution Steps
Use DFS or BFS to traverse the adjacent pixels with the same starting color and update their color to the new color.
Optimal JS Solution
function floodFill(image, sr, sc, color) {
const startColor = image[sr][sc];
if (startColor === color) return image;
const dfs = (r, c) => {
if (r < 0 || c < 0 || r >= image.length || c >= image[0].length || image[r][c] !== startColor) return;
image[r][c] = color;
dfs(r + 1, c); dfs(r - 1, c); dfs(r, c + 1); dfs(r, c - 1);
};
dfs(sr, sc);
return image;
}Edge Cases & Pitfalls
- Always consider empty or null inputs.
- Watch out for off-by-one index errors.
Mark this page when you finish learning it.
Last updated on
Spotted something unclear or wrong on this page?