Show problems as
Classic problem #733EasyArrayDepth-First SearchBreadth-First SearchMatrix

Flood Fill

Real-world version: Recode the Contiguous Soil Block
Tracked in this browser only
Read Flood Fill on LeetCode(opens in a new tab)

The statement here is our own: the same inputs, outputs and technique.

A field survey stores one soil code per plot in a rectangular grid. plots[r][c] is the code recorded for the plot in row r, column c.

A soil treatment is booked for the plot at row sr, column sc. From there it creeps into any plot that shares a full edge with a treated plot (above, below, left or right) and carries the same code as the booked plot, and it keeps creeping outward from every plot it reaches. Plots that meet only at a corner are never reached this way.

Every plot the treatment reaches takes the code code. Apply the change to the grid you were given and return that same grid. If code is already the booked plot's code, the grid comes back exactly as it arrived.

Examples

Example 1

Input
plots = [[7, 7, 2], [7, 2, 7], [2, 7, 7]], sr = 0, sc = 0, code = 4
Output
[[4, 4, 2], [4, 2, 7], [2, 7, 7]]

The booked plot carries code 7. The plot to its right and the plot below it also carry 7 and share an edge with it, so three plots take code 4. The 7s in the lower right meet that group only at a corner, so they keep their code.

Example 2

Input
plots = [[3, 3], [3, 3]], sr = 1, sc = 1, code = 3
Output
[[3, 3], [3, 3]]

The requested code is already the booked plot's code, so every plot the treatment reaches keeps the value it had.

Example 3

Input
plots = [[1, 2], [2, 1]], sr = 0, sc = 0, code = 2
Output
[[2, 2], [2, 1]]

The booked plot carries code 1 and neither plot sharing an edge with it carries 1, so only that one plot takes code 2. The 1 in the opposite corner is untouched.

Constraints

  • m == plots.length
  • n == plots[i].length
  • 1 <= m, n <= 50
  • 0 <= plots[i][j], code < 2^16
  • 0 <= sr < m
  • 0 <= sc < n

The signature

The editor starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.

Python
def recode_soil_block(plots: list[list[int]], sr: int, sc: int, code: int) -> list[list[int]]:
Java
public int[][] recodeSoilBlock(int[][] plots, int sr, int sc, int code)