Flood Fill

Given a 2D image and a starting pixel, recolor the entire connected region of the starting pixel using four-directional adjacency and return the updated image. Pattern focus: Flood fill. Traverse one connected component and paint it with the new color.

Input Format

image = 2D integer matrix, sr/sc = start cell, color = new color

Output Format

updated image after flood fill

Constraints

  • 1 <= rows * cols <= 10^5
  • 0 <= image[i][j], color <= 10^4

Examples

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]]

Explanation:

The connected component containing (1,1) is recolored from 1 to 2.

Example 2:

Input:

image = [[0,0,0],[0,1,1]]
sr = 1
sc = 1
color = 1

Output:

[[0,0,0],[0,1,1]]

Explanation:

The new color is the same as the old color, so the image remains unchanged.

Example 3:

Input:

image = [[0]]
sr = 0
sc = 0
color = 7

Output:

[[7]]

Explanation:

A single pixel is recolored.

Loading...
Flood Fill - Graph Traversal DSA Problem