Coloring A Border - Problem
Coloring A Border is a fascinating grid traversal problem that combines graph theory with practical visualization concepts.
You're given an
What is a border? A cell in the connected component is part of the border if:
โข It's on the edge of the grid (first/last row/column), OR
โข It's adjacent to at least one cell that's NOT part of the same connected component
Goal: Return the modified grid after coloring the border of the connected component containing
You're given an
m x n integer matrix grid where each cell represents a colored square, and three integers: row, col, and color. Your task is to identify a connected component (a group of adjacent cells with the same color) starting from grid[row][col], find its border, and color that border with the new color.What is a border? A cell in the connected component is part of the border if:
โข It's on the edge of the grid (first/last row/column), OR
โข It's adjacent to at least one cell that's NOT part of the same connected component
Goal: Return the modified grid after coloring the border of the connected component containing
grid[row][col]. Input & Output
example_1.py โ Basic Connected Component
$
Input:
grid = [[1,1],[1,2]], row = 0, col = 0, color = 3
โบ
Output:
[[3,3],[3,2]]
๐ก Note:
The connected component starting at (0,0) consists of cells with value 1: (0,0), (0,1), and (1,0). All these cells are border cells because they're either on the grid boundary or adjacent to cell (1,1) which has a different color. So all three cells get colored with 3.
example_2.py โ Interior vs Border Cells
$
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]]
๐ก Note:
The entire grid forms one connected component of 1's. The center cell (1,1) is interior (surrounded by same-colored cells), while all edge cells are border cells. Only the border gets colored with 2, leaving the center cell unchanged.
example_3.py โ Same Color Edge Case
$
Input:
grid = [[1,1],[1,2]], row = 0, col = 0, color = 1
โบ
Output:
[[1,1],[1,2]]
๐ก Note:
Since the target color (1) is the same as the original color of the connected component, no changes are made to the grid.
Constraints
- m == grid.length
- n == grid[i].length
- 1 โค m, n โค 50
- 1 โค grid[i][j], color โค 1000
- 0 โค row < m
- 0 โค col < n
Visualization
Tap to expand
Understanding the Visualization
1
Identify Component
Starting from the given cell, use DFS to find all connected cells with the same color
2
Detect Borders
A cell is a border if it's on the grid edge OR has a neighbor with different color
3
Apply Color
Color all identified border cells with the new color
Key Takeaway
๐ฏ Key Insight: Use DFS with temporary negative marking to simultaneously discover the connected component and identify border cells in a single traversal, achieving optimal O(mรn) time complexity.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code