medium +20 pts

Flood Fill Algorithm

Implement the classic flood fill on a 2D grid.

You are given a 2D grid of integers `image` (list of lists) and a starting pixel `(sr, sc)`. Your task is to implement the flood fill operation: change the color of the starting pixel and all connected pixels (up/down/left/right) that have the same original color as the starting pixel to a new color `newColor`. Return the modified grid. Write a function `flood_fill(image, sr, sc, new_color)` that returns the modified grid as a list of lists of integers.

Constraints

- `1 <= len(image) <= 50` – number of rows. - `1 <= len(image[0]) <= 50` – number of columns. - `0 <= sr < len(image)` - `0 <= sc < len(image[0])` - `0 <= image[i][j] < 256` - `0 <= new_color < 256` - The grid must be modified in place and returned.

Example

>>> flood_fill([[1,1,1],[1,1,0],[1,0,1]], 1, 1, 2)
[[2,2,2],[2,2,0],[2,0,1]]
>>> flood_fill([[0,0,0],[0,0,0]], 0, 0, 1)
[[1,1,1],[1,1,1]]
>>> flood_fill([[1,2,3],[4,5,6]], 0, 0, 9)
[[9,2,3],[4,5,6]]
20 points ~25 min

Recent Submissions

No submissions yet — hit Run Tests to try!

Hints

If the starting pixel already has the new color, return the image unchanged.
Use a queue (BFS) or recursion (DFS) to visit all adjacent cells with the same original color.
Remember to change the color before or when visiting each cell to avoid infinite loops.
Valid neighbors are only within grid bounds (up, down, left, right).
Python 3
All tests passed!
Test Results
Press Ctrl+Enter or click Run Tests to execute your code.