Flood Fill

Try to solve the Flood Fill problem.


We are given the following values as input to begin with:

  • The coordinates of a source cell, i.e., sr and sc.

  • A target value, target.

  • An (m×n)(m \times n) grid.

Our task is to perform flood fill by updating the values of the four directionally connected cells, which have the same value as the source cell with the target value.

How to perform flood fill:

Suppose that a (4×4)(4 \times 4) grid has a source value of 11 at coordinates [1,1][1, 1]. We perform flood fill on its neighboring cells only if they have the same source value as this cell. Once all adjacent cells are updated, return the new grid after performing flood fill.

If no neighboring cell has a value equal to the source cell, only update the source cell with the target value and return the updated grid.


  • 11 \leq grid.length, grid[i].length 30\leq 30

  • 00 \leq grid[i][j], target 216\leq 2^{16}

  • 00 \leq sr <\lt grid.length

  • 00 \leq sc <\lt grid[i].length


Create a free account to view this lesson.

By signing up, you agree to Educative's Terms of Service and Privacy Policy