Python coding

Repaint a connected patch

An image is a non-empty grid image of integers, one color per pixel. Starting from the pixel in row row and column col, repaint with color that pixel and every pixel you can reach from it by stepping up, down, left or right through pixels of the same color as the start. Return the image after repainting; every other pixel keeps its color.

Diagonal steps don't count, and color may already be the start's color.

  • repaint([[1,1,1],[1,1,0],[1,0,1]], 1, 1, 2) → [[2,2,2],[2,2,0],[2,0,1]]
  • repaint([[0,0,0],[0,0,0]], 0, 0, 0) → [[0,0,0],[0,0,0]]
  • repaint([[1,0],[0,1]], 0, 0, 3) → [[3,0],[0,1]]
Ctrl/⌘ + Enter runs · Tab indents
Hint 1

The pixels to repaint form one connected region: run a DFS or BFS from the start that only steps onto pixels of the start's original color.

Hint 2

Paint a pixel when you push it onto the stack or queue: the new color then also marks it as visited, so no pixel enters twice.

Hint 3

If color equals the start's color, return right away: painted pixels would still look unvisited and the search would never end.

Solution and why it works
pythonO(R·C), R × C = image size · O(R·C) for the stack
def repaint(image: list[list[int]], row: int, col: int, color: int) -> list[list[int]]:
    old = image[row][col]
    if old == color:
        return image                       # nothing changes, and the search would never end
    image[row][col] = color
    stack = [(row, col)]
    while stack:
        r, c = stack.pop()
        for nr, nc in ((r + 1, c), (r - 1, c), (r, c + 1), (r, c - 1)):
            if 0 <= nr < len(image) and 0 <= nc < len(image[0]) and image[nr][nc] == old:
                image[nr][nc] = color      # paint on push: the new color marks it visited
                stack.append((nr, nc))
    return image

The patch is everything reachable from the start through pixels of its original color, so one DFS or BFS finds it, visiting each pixel at most once: O(R·C). Painting a pixel as you push it doubles as the visited mark. That shortcut has a trap: when color equals the old color, a painted pixel still matches and the search loops forever, so return the image unchanged first. An explicit stack also avoids Python's recursion limit on large patches.