Perform Connected Component Recolor on Grid
Trees & GraphsAuto-graded · 20 test casesLast updated
Perform a flood-fill recoloring on a 2D integer grid while avoiding call stack overflow and preserving the original input.
Given a 2D grid of integers representing colors, a target coordinate (row, col), and a replacement color new_color, recolor the connected component containing the target cell with new_color.
A cell belongs to the same connected component as the starting cell (row, col) if it shares the starting cell's original color and can be reached via a sequence of orthogonal (up, down, left, right) steps through cells of that same original color.
Requirements and Rules:
- Return a new grid with the updated colors; do not modify the input grid in place.
- If the original color at
(row, col)is already equal tonew_color, return a duplicate of the original grid without modifications. - If the grid is empty (0 rows or 0 columns), return a deep copy of the grid.
- Assume
(row, col)is within valid grid bounds whenever the grid is non-empty.
Constraints
0 <= len(grid) <= 5000 <= len(grid[i]) <= 5000 <= grid[i][j] <= 10^90 <= row < len(grid)0 <= col < len(grid[0])0 <= new_color <= 10^9
Examples
Example 1
Input: infect_color_region([[1, 1, 0], [1, 0, 0], [0, 0, 1]], 0, 0, 2)
Output: [[2, 2, 0], [2, 0, 0], [0, 0, 1]]
Example 2
Input: infect_color_region([[0, 0, 1], [0, 1, 1], [1, 1, 0]], 1, 1, 0)
Output: [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
Hints
Hint 1
Check whether the original color at the target location is already equal to `new_color` to prevent endless loops.
Hint 2
Use an explicit data structure (such as a stack or queue) to implement an iterative traversal instead of recursion to avoid call stack limits on large grids.
Hint 3
Mark cells with the new color as soon as they are pushed onto the traversal structure to avoid duplicate processing.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The problem asks us to perform a standard flood-fill (or connected-component recoloring) on a 2D matrix without mutating the original input.
- Defensive Copy: First, create a deep copy of
gridso the input array remains unchanged. - Early Return: Read
original_color = result[row][col]. Iforiginal_color == new_color, return the copied grid immediately. This prevents infinite loops and unnecessary work. - Iterative Graph Traversal (DFS/BFS): To handle large grid dimensions safely without encountering stack overflow errors from deep recursion, use an explicit stack or queue on the heap.
- Marking Visited Cells: Change the cell's value in
resulttonew_colorat the exact moment it is pushed onto the stack. Sinceoriginal_color != new_color, updating the cell serves as a visited marker, ensuring no cell is enqueued or pushed multiple times.
Complexity Analysis
- Time Complexity: $\mathcal{O}(R \cdot C)$, where $R$ is the number of rows and $C$ is the number of columns. Copying the grid takes $\mathcal{O}(R \cdot C)$ time. The traversal visits each cell in the connected component at most once and inspects its four neighbors, taking $\mathcal{O}(K)$ time where $K \le R \cdot C$ is the component size.
- Space Complexity: $\mathcal{O}(R \cdot C)$ to store the newly created output grid, plus $\mathcal{O}(K)$ extra space for the explicit traversal stack.
from typing import List
def infect_color_region(grid: List[List[int]], row: int, col: int, new_color: int) -> List[List[int]]:
if not grid or not grid[0]:
return [row_vec[:] for row_vec in grid]
result = [row_vec[:] for row_vec in grid]
rows, cols = len(result), len(result[0])
original_color = result[row][col]
if original_color == new_color:
return result
result[row][col] = new_color
stack = [(row, col)]
while stack:
curr_r, curr_c = stack.pop()
for dr, dc in ((-1, 0), (1, 0), (0, -1), (0, 1)):
nr, nc = curr_r + dr, curr_c + dc
if 0 <= nr < rows and 0 <= nc < cols and result[nr][nc] == original_color:
result[nr][nc] = new_color
stack.append((nr, nc))
return result