KatInterview

Perform Connected Component Recolor on Grid

Trees & GraphsAuto-graded · 20 test cases
MediumAuto-gradedTrees & Graphsbfs-dfsmatrixflood-fill

Last 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 to new_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) <= 500
  • 0 <= len(grid[i]) <= 500
  • 0 <= grid[i][j] <= 10^9
  • 0 <= 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.