Flood Fill - aloalgo

Flood Fill

Medium

You are given a 2D grid of integers image representing pixel colors, a starting position (x, y), and a new color.

Your task is to perform a flood fill starting from pixel image[x][y]. Change the color of the starting pixel and all connected pixels that share the same original color as the starting pixel to the new color.

You may assume that:

  • Two pixels are connected if they are adjacent horizontally or vertically (not diagonally).
  • The grid has at least one row and one column.
  • x and y are valid indices within the grid.

Do not return anything, instead modify the input image directly.

Example 1

Inputs
image = [
  [1, 1, 1],
  [1, 1, 0],
  [1, 0, 1]
]
x = 1
y = 1
color = 2
Output
[
  [2, 2, 2],
  [2, 2, 0],
  [2, 0, 1]
]
Explanation:

The starting pixel at (1, 1) has color 1. All pixels connected to it with color 1 are changed to 2. The pixels at (2, 2) and the 0-colored pixels are not connected to the starting pixel by same-colored neighbors.

Example 2

Inputs
image = [
  [0, 0, 0],
  [0, 0, 0]
]
x = 0
y = 0
color = 2
Output
[
  [2, 2, 2],
  [2, 2, 2]
]
Explanation:

All pixels share the same color 0 and are connected, so the entire grid is filled with color 2.

Loading...
Inputs
image = [
  [1, 1, 1],
  [1, 1, 0],
  [1, 0, 1]
]
x = 1
y = 1
color = 2
Output
[
  [2, 2, 2],
  [2, 2, 0],
  [2, 0, 1]
]

Hello! I am your ✨ AI assistant. I can provide you hints, explanations, give feedback on your code, and more. Just ask me anything related to the problem you're working on!