Flood Fill

Try to solve the Flood Fill problem.

Statement

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.

Constraints:

  • 1≤1 \leq grid.length, grid[i].length ≤30\leq 30

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

  • 0≤0 \leq sr <\lt grid.length

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

Examples

Create a free account to view this lesson.

Continue your learning journey with a 14-day free trial.

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