Coloring A Border Problem
Description
LeetCode Problem 1034.
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).
You should color the border of the connected component that contains the square grid[row][col] with color.
Return the final grid.
Example 1:
Input: grid = [[1,1],[1,2]], row = 0, col = 0, color = 3
Output: [[3,3],[3,2]]
Example 2:
Input: grid = [[1,2,2],[2,3,2]], row = 0, col = 1, color = 3
Output: [[1,3,3],[2,3,3]]
Example 3:
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]]
Constraints:
m == grid.lengthn == grid[i].length1 <= m, n <= 501 <= grid[i][j], color <= 10000 <= row < m0 <= col < n
Solution
Approach: BFS Over the Component, Recolor at the End
First find the connected component of grid[row][col]: a BFS that starts at that cell and moves to neighbors with the same original color original, using a seen table so no cell is visited twice.
While visiting a cell, look at its four neighbors. If a neighbor is outside the grid, or has a color other than original, the cell is on the border, so we remember it. Otherwise the neighbor is part of the component, and we push it if it has not been seen yet.
Only after the search ends do we paint all remembered border cells with color. Painting during the search would be a bug: an inner cell next to an already painted border cell would see a "different" color and wrongly be treated as a border cell too (and if color happens to equal another color in the grid, the search could even leak into it). Collecting first and painting afterwards keeps every check on the original colors.
Complexity: O(m * n) time and space for the seen table, the queue and the list of border cells.
from collections import deque
class Solution:
def colorBorder(self, grid: List[List[int]], row: int, col: int, color: int) -> List[List[int]]:
m, n = len(grid), len(grid[0])
original = grid[row][col]
seen = [[False] * n for _ in range(m)]
seen[row][col] = True
queue = deque([(row, col)])
border = []
while queue:
i, j = queue.popleft()
for x, y in ((i - 1, j), (i + 1, j), (i, j - 1), (i, j + 1)):
if not (0 <= x < m and 0 <= y < n) or grid[x][y] != original:
border.append((i, j)) # next to the grid's edge or to another component
elif not seen[x][y]:
seen[x][y] = True
queue.append((x, y))
# Recolor only at the end, so the search above still sees the original colors.
for i, j in border:
grid[i][j] = color
return grid