733. Flood Fill
Given a 2D grid, a starting pixel, and a new color, recolor the starting pixel and every pixel connected to it (up/down/left/right) that shares its original color.
def flood_fill(image, sr, sc, color):
old = image[sr][sc]
if old == color:
return image
def dfs(r, c):
if (
0 <= r < len(image)
and 0 <= c < len(image[0])
and image[r][c] == old
):
image[r][c] = color
dfs(r + 1, c)
dfs(r - 1, c)
dfs(r, c + 1)
dfs(r, c - 1)
dfs(sr, sc)
return image
A grid is just a graph where each cell is a node connected to its four neighbors. DFS from the start cell, recoloring as it goes, naturally stops spreading once it hits a cell that's already a different color (the guard clause at the top of dfs).