Coloring A Border

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
class Solution:
    def colorBorder(self, grid: List[List[int]], row: int, col: int, color: int) -> List[List[int]]:
        seen = set()
        m = len(grid)
        n = len(grid[0])

        def dfs(x, y):
            if (x, y) in seen:
                return True
            if not (0 <= x < m and 0 <= y < n and grid[x][y] == grid[row][col]):
                return False
            seen.add((x, y))
            connected_adjacent_cells = dfs(x + 1, y) + dfs(x - 1, y) + dfs(x, y + 1) + dfs(x, y - 1)
            if connected_adjacent_cells < 4:
                grid[x][y] = color
            return True
        dfs(row, col)
        return grid