DIY: Flood Fill
Solve the interview question "Flood Fill" in this lesson.
We'll cover the following
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 newColor
, 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 newColor
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 newColor
. The following is an example input:
image = [
[1,1,1],
[1,1,0],
[1,0,1]
]
sr = 1
sc = 1
newColor = 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 floodFill(image, sr, sc, newColor)
function, where image
represents the initial image, sr
is the row value, sc
is the column value, and newColor
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 70+ hands-on prep courses.