Flood Fill

Graphs, problem 1 of 8

Flood Fill

Easy

LC #733

griddfsmatrix

Not attempted yet

An image is a grid of integers (pixel colours). Starting from pixel (sr, sc), recolour it and every pixel connected to it up, down, left or right that has the same original colour as the start. Return the image.

This is the paint-bucket tool: diagonal pixels don't count.

Example 1

Input: image = [[1,1,1],[1,1,0],[1,0,1]],
       sr = 1, sc = 1, color = 2
Output: [[2,2,2],[2,2,0],[2,0,1]]

The bottom-right 1 only touches the region diagonally, so it keeps its colour.

Example 2

Input: image = [[0,0,0],[0,0,0]],
       sr = 0, sc = 0, color = 0
Output: [[0,0,0],[0,0,0]]

The new colour equals the old one: nothing changes.

Example 3

Input: image = [[0,0,0],[0,1,1]],
       sr = 1, sc = 1, color = 3
Output: [[0,0,0],[0,3,3]]

Constraints

  • 1 <= rows, cols <= 150
  • 0 <= image[r][c], color < 2^16
  • (sr, sc) is inside the image
  • Big regions are tested: a recursive DFS may exceed Python's recursion limit, so prefer a stack or queue.

Python

Loading draft…

Test results

7 tests available

No results yet

Run tests your code against the examples; Submit runs the hidden tests too.

3 examples, 4 hidden

Run examples, then submit all tests.