Skip to main content
CodeOath
← All problems

Problem

Flood Fill

Easy
  • graphs
  • dfs
  • matrix

image is a grid of integers, and each integer is the color of one pixel. Repaint the region that contains the pixel at row sr and column sc. That pixel, and every pixel you can reach from it by steps up, down, left or right without leaving pixels of its original color, becomes color. Diagonal steps do not count.

Return the repainted image. If the starting pixel is already color, return the image as it is.

Example 1
Input
image = [[4, 4, 7], [4, 7, 7], [4, 4, 4]], sr = 0, sc = 0, color = 9
Output
[[9, 9, 7], [9, 7, 7], [9, 9, 9]]
Explanation

all six 4 pixels are linked to the starting pixel by up, down, left or right steps, so they all become 9. The three 7 pixels are a different color and stay.

Example 2
Input
image = [[2, 2, 6], [2, 6, 6]], sr = 0, sc = 0, color = 2
Output
[[2, 2, 6], [2, 6, 6]]
Explanation

the starting pixel is already 2, so there is nothing to repaint.

Example 3
Input
image = [[5, 0, 0], [0, 5, 0], [0, 0, 5]], sr = 1, sc = 1, color = 8
Output
[[5, 0, 0], [0, 8, 0], [0, 0, 5]]
Explanation

the center 5 has a 0 above, below, left and right of it. The other 5 pixels touch it only at a corner, which does not count, so only the center changes.

Constraints:

  • image has at least one row, and every row has the same length
  • 0 <= sr < image.length and 0 <= sc < image[0].length

Tab indents. Press Esc, then Tab to leave the editor.

Run your code to see every test here. Nothing is submitted or recorded.