# 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]]
# Solution
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()
add_to_border = False
if r in [0, len(grid) - 1] or c in [0, len(grid[0]) - 1]:
add_to_border = True
for delta in [(0, 1), (0, -1), (1, 0), (-1, 0)]:
if 0 <= r + delta[0] < len(grid) and 0 <= c + delta[1] < len(grid[0]):
if (r + delta[0], c + delta[1]) not in queued and grid[r + delta[0]][c + delta[1]] == orig_color:
components.append((r + delta[0], c + delta[1]))
queued.add((r + delta[0], c + delta[1]))
if grid[r+delta[0]][c+delta[1]] != orig_color:
add_to_border = True
if add_to_border:
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):
add_to_border = False
if (r, c) in explored:
return
explored.add((r, c))
if r in [0, len(grid) - 1] or c in [0, len(grid[0]) - 1]:
add_to_border = True
for delta in [(0, 1), (0, -1), (1, 0), (-1, 0)]:
if not (0 <= r + delta[0] < len(grid) and 0 <= c + delta[1] < len(grid[0])) or (r + delta[0], c + delta[1]) in explored:
continue
if grid[r + delta[0]][c + delta[1]] == grid[r][c]:
explore(r + delta[0], c + delta[1])
else:
add_to_border = True
if add_to_border:
borders.append((r, c))
explore(r, c)
for r, c in borders:
grid[r][c] = color
return grid
# Code (C++)
Approach 1:
Approach 2: