Flood Fill
Paint-bucket: recolor the connected region of same-colored pixels around (sr, sc).
Intuition
It's DFS/BFS on the grid: from the start pixel, spread to 4-neighbours sharing the original color, repainting as you go. Repainting doubles as the visited-marker.
Identical machinery to counting islands, minus the outer scan — one component, one flood. The reusable shape is: validate bounds and the match condition at the top of the recursive function, mark on entry, then recurse in all four directions. Every grid-flood problem is this function with a different mark and a different match test.
Approach
Remember the original color
Only pixels matching it spread the fill; the new color is the paint.
DFS with bounds checks
Recurse on 4 neighbours inside the grid with the old color. Repaint before recursing to avoid revisits.
The self-fill trap
If newColor == oldColor the recursion never terminates — return immediately in that case.
Solution & live demo
Common pitfalls
Not returning early when the new colour equals the old
old = image[sr][sc] def fill(r, c): ...
old = image[sr][sc] if old == color: return image
Painting a cell its existing colour doesn't change it, so the image[r][c] == old test stays true forever and neighbours recurse into each other until the stack overflows. The guard is what guarantees progress — this is the single most common way to hang this problem.
Matching against the starting cell's live value
if image[r][c] == image[sr][sc]:
old = image[sr][sc] if image[r][c] == old:
The origin gets repainted on the very first step, so the comparison target changes mid-traversal and the fill stops after one cell. Capture the original colour before any mutation.
Filling diagonally
fill(r+1, c+1); fill(r-1, c-1)
fill(r+1, c); fill(r-1, c); fill(r, c+1); fill(r, c-1)
The problem defines connectivity as 4-directional. Adding diagonals bleeds the fill across regions that only touch at a corner and are meant to stay separate.
Edge cases
Early return — otherwise infinite loop.
Only it changes; neighbours differ in color.