You are given an m x n integer matrix grid, and three integers row, col, and color. Each value in the grid represents the color of the grid square at that location.
Two squares are called adjacent if they are next to each other in any of the 4 directions. Two squares belong to the same connected component if they have the same color and they are adjacent.
The border of a connected component is all the squares in the connected component that are either adjacent to (at least) a square not in the component, or on the boundary of the grid (the first or last row or column).
Color the border of the connected component that contains the square grid[row][col] with color. Return the final grid.
Function Signature
def color_border(grid: list[list[int]], row: int, col: int, color: int) -> list[list[int]]:
Rules
-
grid[r][c]
is the square in row
r
and column
c
.
-
Adjacency is 4-directional (up, down, left, right). Diagonal squares are not adjacent.
-
A connected component is every square reachable from a starting square through a chain of adjacent squares that all share its color.
-
Decide which squares are border squares from the colors in the input grid, then recolor them. Recoloring never changes which squares count as border.
-
Only the border squares of the component that contains
(row, col)
change. Every other square keeps its value. Modifying
grid
in place and returning it is fine.
Constraints
-
m == grid.length
-
n == grid[i].length
-
1 <= m, n <= 50
-
1 <= grid[i][j], color <= 1000
-
0 <= row < m
-
0 <= col < n
Examples
Input: grid = [[1,1],[1,2]], row = 0, col = 0, color = 3
Output: [[3,3],[3,2]]
The component of (0,0) is the three 1s. All of them touch either the grid edge or the square with value 2, so all are border squares and become 3.
Input: grid = [[1,2,2],[2,3,2]], row = 0, col = 1, color = 3
Output: [[1,3,3],[2,3,3]]
The component of (0,1) is the 2s at (0,1), (0,2) and (1,2), and each lies on the grid edge, so all three become 3. The 2 at (1,0) has only a 1 and a 3 as neighbors, so it is a separate component and stays 2.
Input: grid = [[1,1,1],[1,1,1],[1,1,1]], row = 1, col = 1, color = 2
Output: [[2,2,2],[2,1,2],[2,2,2]]
All nine squares form one component. The center square is not on the grid edge and all four of its neighbors are in the component, so it is the only square that keeps its color.