## # 1034. Coloring A Border

Given a 2-dimensional grid of integers, each value in the grid represents the color of the grid square at that location.

Two squares belong to the same connected component if and only if they have the same color and are next to each other in any of the 4 directions.

The border of a connected component is all the squares in the connected component that are either 4-directionally adjacent to a square not in the component, or on the boundary of the grid (the first or last row or column).

Given a square at location (r0, c0) in the grid and a color, color the border of the connected component of that square with the given color, and return the final grid.

Example 1:

``````Input: grid = [[1,1],[1,2]], r0 = 0, c0 = 0, color = 3
Output: [[3, 3], [3, 2]]
``````

Example 2:

``````Input: grid = [[1,2,2],[2,3,2]], r0 = 0, c0 = 1, color = 3
Output: [[1, 3, 3], [2, 3, 3]]
``````

Example 3:

``````Input: grid = [[1,1,1],[1,1,1],[1,1,1]], r0 = 1, c0 = 1, color = 2
Output: [[2, 2, 2], [2, 1, 2], [2, 2, 2]]
``````

Approach 1: BFS.

Approach 2: DFS.

### # Code (Python)

Approach 1:

``````    def colorBorder(self, grid: List[List[int]], r: int, c: int, color: int) -> List[List[int]]:
# BFS
orig_color = grid[r][c]
components = deque([(r, c)])
queued = set([(r, c)])
borders = []
while components:
r, c = components.popleft()
if r in [0, len(grid) - 1] or c in [0, len(grid) - 1]:
for delta in [(0, 1), (0, -1), (1, 0), (-1, 0)]:
if 0 <= r + delta < len(grid) and 0 <= c + delta < len(grid):
if (r + delta, c + delta) not in queued and grid[r + delta][c + delta] == orig_color:
components.append((r + delta, c + delta))
queued.add((r + delta, c + delta))
if grid[r+delta][c+delta] != orig_color:
borders.append((r, c))
for r, c in borders:
grid[r][c] = color
return grid
``````

Approach 2:

``````    def colorBorder(self, grid: List[List[int]], r: int, c: int, color: int) -> List[List[int]]:
# DFS
borders = []
explored = set([])

def explore(r, c):
if (r, c) in explored:
return
if r in [0, len(grid) - 1] or c in [0, len(grid) - 1]:
for delta in [(0, 1), (0, -1), (1, 0), (-1, 0)]:
if not (0 <= r + delta < len(grid) and 0 <= c + delta < len(grid)) or (r + delta, c + delta) in explored:
continue
if grid[r + delta][c + delta] == grid[r][c]:
explore(r + delta, c + delta)
else: