This is the paint-bucket tool. Starting from one cell, recolor every cell in its connected same-color region.
Write flood_fill(grid, sr, sc, new_color) that:
If the start color already equals new_color, return the grid unchanged. Otherwise you would loop forever. Reuse neighbors from Step 1 to walk the region with a DFS stack.
def neighbors(grid, r, c):
"""Return in-bounds 4-directional neighbor coords: up, down, left, right."""
rows = len(grid)
cols = len(grid[0]) if rows else 0
result = []
for nr, nc in ((r - 1, c), (r + 1, c), (r, c - 1), (r, c + 1)):
if 0 <= nr < rows and 0 <= nc < cols:
result.append((nr, nc))
return result
def flood_fill(grid, sr, sc, new_color):
"""Fill the connected region of the start cell's color with new_color."""
# TODO: DFS from (sr, sc), recoloring cells that match the start color
pass
The editor and the test runner need a wide screen. Open this page on a desktop browser and your progress will be waiting.
This is the paint-bucket tool. Starting from one cell, recolor every cell in its connected same-color region.
Write flood_fill(grid, sr, sc, new_color) that:
If the start color already equals new_color, return the grid unchanged. Otherwise you would loop forever. Reuse neighbors from Step 1 to walk the region with a DFS stack.
Press Run Tests or ββ© to check your solution.