iq.lab
Python starts when a code cell comes near or you run one
easyDepth-first search target 15 min

Flood fill

image is a grid of pixels, a list of rows, and image[r][c] is the color of the pixel in row r and column c, stored as a whole number. You also get a starting pixel at row row and column col, and a new color.

Paint the region of the starting pixel with color. The region is the starting pixel plus every pixel you can reach from it by stepping up, down, left or right (not diagonally), only through pixels that have the starting pixel's original color. Pixels outside the region keep their color.

Return the painted grid. You may change image in place and return it.

Example 1
Inputimage = [[1, 1, 0], [0, 1, 0], [1, 0, 1]], row = 0, col = 0, color = 5Output[[5, 5, 0], [0, 5, 0], [1, 0, 1]]

The three 1s joined by sides become 5. The 1s in the bottom corners touch the region only at a corner, so they stay 1.

Example 2
Inputimage = [[0, 0, 0], [0, 7, 7], [0, 7, 0]], row = 2, col = 2, color = 4Output[[0, 0, 0], [0, 7, 7], [0, 7, 4]]

The 0 in the bottom-right corner is walled in by 7s, so its region is that one pixel. The other 0s are not connected to it.

Example 3
Inputimage = [[3, 3], [3, 1]], row = 0, col = 0, color = 3Output[[3, 3], [3, 1]]

The new color is the old color, so nothing changes.

Constraints
  • 1 ≤ number of rows, number of columns ≤ 50

  • Colors, in the image and in color, are whole numbers from 0 to 65,535.

  • 0 ≤ row < number of rows and 0 ≤ col < number of columns

Plan it first

Write a line for each before you code, then say them out loud. Compare with the Approach tab afterwards.

⌘+Enter runs 0:00Python starts when a code cell comes near or you run one
Run examples checks the examples. Submit runs every test, including edge cases and, when the problem has one, a speed check on a large input.