Menu
CoddyTech

Flood Fill

EasyGraphspython iconjava iconcpp iconc iconjs icon+10

An image is a grid of whole numbers, where each number is the color of one pixel. You get the image as a list of rows, a starting pixel at row sr and column sc, and a new color. Repaint the region that holds the starting pixel: every pixel of the starting pixel's color that you can reach from it by stepping up, down, left or right through pixels of that same color. Return the image after the repaint.

Function

floodFill(image: integer-2d-array, sr: integer, sc: integer, color: integer) → integer-2d-array
imageinteger-2d-array
the image as a list of rows, one number per pixel
srinteger
the row of the starting pixel, counted from 0
scinteger
the column of the starting pixel, counted from 0
colorinteger
the new color for the region
Returnsinteger-2d-array
the image after the region is repainted

Constraints

  • 1 ≤ image.length ≤ 80
  • 1 ≤ image[i].length ≤ 80
  • Every row has the same length.
  • 0 ≤ image[i][j], color ≤ 65535
  • 0 ≤ sr < image.length and 0 ≤ sc < image[0].length

Examples

Input
image = [[1, 1, 0], [1, 0, 1], [1, 1, 1]]sr = 0sc = 0color = 5
Output
[[5, 5, 0], [5, 0, 5], [5, 5, 5]]
Explanation
The start holds color 1. All seven 1s link to it through side-sharing 1s, down the left column, along the bottom row and up the right edge, so all become 5. The two 0s keep their color.
challenge icon

Follow-up

How would your solution change if pixels that touch only at a corner also counted as connected?

Reset code
def floodFill(image, sr, sc, color):
    # Write code here

Test #1

Test #2

Test #3

Arguments

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

Expected Output

[[5, 5, 0], [5, 0, 5], [5, 5, 5]]