Problem Description
Given an m x n grid where each cell has a color value, the goal is to change the color of the border of the connected component that includes the cell grid[row][col]. A connected component consists of cells with the same color that are adjacent (up, down, left, right). A cell is considered a border if it is either adjacent to a cell of a different color or lies on the boundary of the grid.
Key Insights
- Identify the connected component starting from grid[row][col] using DFS or BFS.
- A cell is on the border if any of its 4 adjacent cells is either out-of-bounds or has a different color.
- After determining all border cells, update their color while keeping the internal area unchanged.
- Tracking visited cells prevents unnecessary reprocessing and infinite loops.
Space and Time Complexity
Time Complexity: O(mn) in the worst case, where m and n are the number of rows and columns. Space Complexity: O(mn) due to the recursion stack (in DFS) or queue (in BFS) and the visited structure.
Solution
We solve the problem by first performing a DFS (or BFS) starting at the given cell (row, col) to traverse its connected component. During the traversal, we check for each cell whether it qualifies as a border cell. A cell is a border cell if:
- It is on the boundary of the grid.
- At least one of its 4 neighbors is not of the same original color. After collecting all the border cells, their color is updated to the given new color. The use of DFS (or BFS) ensures that every cell in the connected component is visited exactly once, resulting in an efficient solution.