1034. 边界着色

exiaohu 于 2021-12-07 发布

题目链接:1034. 边界着色

广度优先搜索,先搜到所有的边界,放在一个列表里,再着色。

from typing import List


class Solution:
    def colorBorder(self, grid: List[List[int]], row: int, col: int, color: int) -> List[List[int]]:
        coords, borders, visited, target = {(row, col)}, set(), set(), grid[row][col]
        if target == color:
            return grid

        is_border = lambda r, c: not all(0 <= r + dx < len(grid) and 0 <= c + dy < len(grid[0]) and grid[r + dx][c + dy] == target for dx, dy in ((0, -1), (-1, 0), (0, 1), (1, 0)))

        while len(coords) > 0:
            r, c = coords.pop()
            visited.add((r, c))

            if is_border(r, c):
                borders.add((r, c))

            for dx, dy in ((0, -1), (-1, 0), (0, 1), (1, 0)):
                if 0 <= r + dx < len(grid) and 0 <= c + dy < len(grid[0]) and grid[r + dx][c + dy] == target and (r + dx, c + dy) not in visited:
                    coords.add((r + dx, c + dy))

        for r, c in borders:
            grid[r][c] = color

        return grid