Image Region Flood Fill
Image segmentation often begins by identifying spatially contiguous regions of similar features or colors. The Flood Fill algorithm is a classic graph traversal technique (typically implemented via Depth-First Search or Breadth-First Search) used to select and modify such a connected area starting from a specific point.
You are given a 2D integer array image representing a digital image. Each integer represents a pixel value (intensity). Given a starting pixel at coordinates (sr, sc) and a newColor, perform a "flood fill" on the image.
The flood fill operation should target the starting pixel, plus any pixels connected 4-directionally (horizontal or vertical) to the starting pixel that share the original color, and so on recursively. All targeted pixels must have their color replaced with newColor. You must return the modified image array.
Constraints:
- The length of image and image[i] will be in the range .
- The given starting pixel will satisfy and .
- The value of each color in image[i][j] and newColor will be an integer in .
- If the original color is the same as the newColor, no action should be taken to prevent infinite recursion/loops.
Example
image = [[1,1,1],[1,1,0],[1,0,1]] sr = 1, sc = 1 newColor = 2
[[2,2,2],[2,2,0],[2,0,1]]
- Inputs:
imageis a grid of pixel colors, the seed is row , column , andnewColoris . The seed pixel's color is , so the region to repaint is every pixel of color that can be reached from the seed by stepping up, down, left or right through color- pixels only. - Growing the region: from the center, the pixels above and to the left are , so they join. From those, the corners and and the pixel are also and join. The pixels and are , so they block the region.
- The isolated : the bottom-right pixel has color , but its only neighbours are and , both . Diagonal contact with the center does not count, so it stays .
- Output: the 6 reached pixels become , giving
[[2,2,2],[2,2,0],[2,0,1]]. The pixels are untouched. - Notice: if
newColoralready equals the seed's color, nothing changes and the image is returned as it is.