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