Recolor a region in a 2D image starting from one cell, replacing all connected cells of the original color.
Given a 2D integer grid representing an image, a starting cell , and a replacement color, change the color of the starting cell and every 4-directionally connected cell with the same original color to the new color.
Two cells are connected if they share a side (up, down, left, or right). Cells with a different color act as barriers. Return the modified grid after the fill operation.
Input Format
- A 2D integer grid
image - Integers
srandscfor the starting row and column - Integer
colorfor the new color
Output Format
Return the grid after recoloring the connected region starting at (sr, sc).
Constraints
1 <= image.length, image[0].length- The grid size is typically small to moderate in interview settings
0 <= sr < image.length0 <= sc < image[0].length- Cell values are integers representing colors
Example 1
Input
image = [[1,1,1],[1,1,0],[1,0,1]], sr = 1, sc = 1, color = 2
Output
[[2,2,2],[2,2,0],[2,0,1]]
Explanation
The starting cell has color 1. All 4-directionally connected cells with color 1 are recolored to 2.
Premium problem context
Unlock deeper context for this problem
Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.