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. The 1 to its right, the 1s down the left column and along the bottom row, and the 1 above the bottom right corner all link to it, so all seven become 5. The two 0s are a different color and keep it.

lock icon+18 hidden tests on Submit

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 cases

Case 1

Case 2

Case 3

Input

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

Expected

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