v9.1.1
Menu

Image Region Flood Fill

easyPROGraphsGraphs, Matrix, DFS/BFSCV - DSA

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 [1,50][1, 50].
  • The given starting pixel will satisfy 0≤sr<image.length0 \leq sr < \text{image.length} and 0≤sc<image[0].length0 \leq sc < \text{image[0].length}.
  • The value of each color in image[i][j] and newColor will be an integer in [0,65535][0, 65535].
  • If the original color is the same as the newColor, no action should be taken to prevent infinite recursion/loops.

Example

Input
image = [[1,1,1],[1,1,0],[1,0,1]]
sr = 1, sc = 1
newColor = 2
Output
[[2,2,2],[2,2,0],[2,0,1]]
Reasoning
  • Inputs: image is a 3×33 \times 3 grid of pixel colors, the seed is row 11, column 11, and newColor is 22. The seed pixel's color is 11, so the region to repaint is every pixel of color 11 that can be reached from the seed by stepping up, down, left or right through color-11 pixels only.
  • Growing the region: from the center, the pixels above (0,1)(0,1) and to the left (1,0)(1,0) are 11, so they join. From those, the corners (0,0)(0,0) and (0,2)(0,2) and the pixel (2,0)(2,0) are also 11 and join. The pixels (1,2)(1,2) and (2,1)(2,1) are 00, so they block the region.
  • The isolated 11: the bottom-right pixel (2,2)(2,2) has color 11, but its only neighbours are (1,2)(1,2) and (2,1)(2,1), both 00. Diagonal contact with the center does not count, so it stays 11.
  • Output: the 6 reached pixels become 22, giving [[2,2,2],[2,2,0],[2,0,1]]. The 00 pixels are untouched.
  • Notice: if newColor already equals the seed's color, nothing changes and the image is returned as it is.

More from CV - DSA

PRO

Editor locked

The code editor is locked for Pro problems. It is only available for free problems. Please upgrade to gain access to the code editor for all problems.

solution.py

Test results

Sign in to run your code against the test cases.