DIY: Flood Fill

Solve the interview question "Flood Fill" in this lesson.

Problem statement

An image is represented by a 2-D array of integers, each integer represents a pixel value of the image between 0 and 65535.

Given a coordinate (sr, sc) representing the flood fill’s starting pixel (row and column) and a pixel value new_color, flood fill the image.

To perform a flood fill, consider the starting pixel, plus any pixels of the same color connected 4-directionally to the starting pixel, plus any pixels connected 4-directionally to those pixels (also with the same color as the starting pixel), and so on. Replace the color of all of the mentioned pixels with the new_color and return the modified image.

Input

The input will be an m x n array of integers, a row value sr, a column value sc, and the new color value new_color. The following is an example input:

image = [
[1,1,1],
[1,1,0],
[1,0,1]
]
sr = 1
sc = 1
new_color = 2

Output

The output will be the same m x n image of integers with pixels updated with the new color value. The following is an example output for the above input:

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

Coding exercise

Implement the flood_fill(image, sr, sc, new_color) function, where image represents the initial image, sr is the row value, sc is the column value, and new_color is the new pixel value. The function will return the same m x n image of integers with the pixels updated with the new color value.

Level up your interview prep. Join Educative to access 80+ hands-on prep courses.