讨论/《深度优先搜索》 - 练习:边框着色/
《深度优先搜索》 - 练习:边框着色

边框即为周围要么是边界,要么是其他颜色的方格,不是边框的方格周围全是相同颜色的方格。用visited数组记录有无访问过。

class Solution:
    def colorBorder(self, grid: List[List[int]], r0: int, c0: int, color: int) -> List[List[int]]:
        row = len(grid)
        col = len(grid[0])
        origColor = grid[r0][c0]
        visited = [[False]*col for _ in range(row)]
        def dfs(x,y)->int:
            if not 0 <= x < row or not 0 <= y < col:
                return 0
            if(visited[x][y] == True): return 1
            if grid[x][y] != origColor: return 0
            visited[x][y] = True
            surround = dfs(x - 1, y)+ dfs(x + 1, y)+ dfs( x, y - 1,)+ dfs(x, y + 1)
            if (surround < 4):
                grid[x][y] = color
            return 1
        dfs(r0,c0)
        return grid